UISearchController使用时,UISearchBar显示的问题

来源:互联网 发布:中国人工智能排名 编辑:程序博客网 时间:2024/06/01 10:00

问题:iOS提供实现搜索功能的SDK:UISearchController(iOS8.0之后)、UISearchDisplayController(iOS8.0之前,iOS8.0之后不建议再使用)。最近在做搜索的时候使用到了UISearchController,恰好NavigationController里有一个手势驱动返回。但是当在搜索页向右滑动界面时,UISearchController的UISearchBar并未跟着view一起向右滑动。考虑了很久,猜测是因为所用到的UISearchController其实并未显示到self.view 才上导致UISearchController的searchBar没有移动。


原因:UISearchController继承自UIViewController,也就是说UISearchController自身也带有一个View。但我们在使用UISearchController的时候并未将UISearchController自带的View添加在self.view上,也就是未指定那个controller显示UISearchController自带View上的控件

解决办法:查找到UIViewController里有一个属性:@property  (nonatomic,assign)BOOL   definesPresentationContext  NS_AVAILABLE_IOS 5;

                           苹果对其使用介绍是:Determines  which  parent  view  controller's  view  should  be  presented  over  for  presentations  of  type   UIModalPresentationCurrentContext. If  no  ancestor  view controller  has  this  flag  set, then  the  presenter  will  be  the  root   view  controller.

                          即:这一属性决定了那个父控制器的View,将会以优先于UIModalPresentationCurrentContext这种呈现方式来展现自己的View。如果没有父控制器设置这一属性,那么展示的控制器将会是根视图控制器。

                          只要在要实现搜索功能的控制器里设置:self.definesPresentationContext = YES;即可实现UISearchController的UISearchBar跟随self.view一起滑动。


代码:

             

        _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];        _searchController.searchResultsUpdater = self;          _searchController.delegate = self;        _searchController.dimsBackgroundDuringPresentation = NO;        _searchController.hidesNavigationBarDuringPresentation = YES;        [self.view addSubview:_searchController.searchBar];    //将searbar添加在self.view上,这一步很重要.        //重点:在合适的地方添加下面一行代码        self.definesPresentationContext = YES;


补充:

      (1)如果不设置:self.definesPresentationContext = YES;那么如果设置了hidesNavigationBarDuringPresentation为YES,在进入编辑模式的时候会导致searchBar看不见(偏移-64)。如果设置了hidesNavigationBarDuringPresentation为NO,在进入编辑模式会导致高度为64的空白区域出现(导航栏未渲染出来)。

      (2)如果设置:self.definesPresentationContext = YES;在设置hidesNavigationBarDuringPresentation为YES,进入编辑模式会正常显示和使用。如果设置了hidesNavigationBarDuringPresentation为NO,在进入编辑模式会导致搜索框向下偏移64.




0 0