如何在iOS 8中使用UISearchController,其中UISearchBar位于导航栏中并具有范围按钮?

Dou*_*ith 29 uinavigationcontroller uisearchbar ios ios8 uisearchcontroller

我正在尝试使用UISearchControlleriOS 8中的新功能,并将其嵌入UISearchBar到我的UINavigationBar.这很容易完成如下:

searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.delegate = self
searchController.searchBar.delegate = self
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
navigationItem.titleView = searchController.searchBar
Run Code Online (Sandbox Code Playgroud)

但是当我添加范围按钮时:

searchController.searchBar.showsScopeBar = true
searchController.searchBar.scopeButtonTitles = ["Posts, Users, Subreddits"]
Run Code Online (Sandbox Code Playgroud)

它添加了背后的按钮UISearchBar,显然看起来很奇怪.

我该怎么做?

小智 22

你正碰到一个"设计问题",scopeBarsearchController它不活跃时,它会被隐藏.

范围栏按钮显示在搜索栏的后面(下方),因为这是搜索栏变为活动状态时的位置,并将其自身动画到导航栏中.

当搜索未激活时,可见范围栏将占用屏幕上的空间,分散内容,并使用户感到困惑(因为范围按钮没有结果可以过滤).

由于您searchBar已经位于titleView中,因此不会显示显示范围栏的(导航和搜索)栏动画.

  • 最简单的选择是定位导航栏下方的搜索栏,并让searchBar动画成标题区域激活时.导航栏将为其高度设置动画,为包含隐藏的范围栏腾出空间.这将全部由搜索控制器处理.
  • 第二个选项,几乎同样简单,就是使用搜索栏按钮图标,该图标将在导航栏上向下searchBarscopeBar向下显示动画.

    - (IBAction)searchButtonClicked:(UIBarButtonItem *)__unused sender {
        self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
        self.searchController.searchResultsUpdater = self;
        self.searchController.hidesNavigationBarDuringPresentation = NO;
        self.searchController.dimsBackgroundDuringPresentation = NO;
        self.definesPresentationContext = YES;
        self.searchController.searchBar.scopeButtonTitles = @[@"Posts", @"Users", @"Subreddits"];
        [self presentViewController:self.searchController animated:YES completion:nil];
    }
    Run Code Online (Sandbox Code Playgroud)
  • 如果你想要searchBar保留在titleView中,那么就不会内置你想要的动画.你必须滚动自己的代码来处理navigationBar高度变化并显示你自己的范围栏(或挂钩到内部,并将内置动画scopeBar放入视图中 并进入视图.

    如果你很幸运,其他人已经编写了willPresentSearchController:代码来处理你想要的转换.

  • 如果你想总是看到一个searchBarscopeBar,你可能不得不使用内置功能scopeBar,并将其替换UISegmentedControl为用户将始终看到的,即使搜索控制器未处于活动状态.

更新:

这个答案建议子类化UISearchController来改变它的searchBar的高度.