我如何使用UISearchController在UISearchBar在我的导航栏,并具有范围button的iOS 8?

我试图从iOS 8使用新的UISearchController ,并将其UISearchBarembedded到我的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 

但是当我添加范围button:

 searchController.searchBar.showsScopeBar = true searchController.searchBar.scopeButtonTitles = ["Posts, Users, Subreddits"] 

它添加了UISearchBar后面的button,显然看起来很奇怪。

我应该怎么做?

你碰到一个“devise问题”,当searchController不活跃的时候searchController被隐藏。

范围栏button显示在search栏的后面(下方),因为当search栏变为活动状态时,范围栏button会自动放置在导航栏中。

当search不活跃时,可见的范围栏将占用屏幕上的空间,分散内容,并混淆用户(因为范围button没有结果进行过滤)。

由于您的searchBar已经位于titleView中,因此不会出现显示范围栏的(导航和search)栏animation。

  • 最简单的select是在导航栏下方findsearch栏,并在激活时让searchBar在标题区域内animation。 导航栏将为其高度设置animation,从而腾出空间来包含隐藏的范围栏。 这将全部由search控制器处理。
  • 第二个选项几乎一样简单,就是使用search栏button图标,这个button图标会将searchBarscopeBaranimation到导航栏的视图中。

     - (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]; } 
  • 如果你想让searchBar保留在titleView中,一个animation做你想要的是不是内置的。你必须滚动自己的代码来处理navigationBar的高度变化,并显示你自己的范围栏(或挂钩到内部,并将内置的scopeBaranimation成视图)。

    如果你是幸运的,别人写了willPresentSearchController:代码来处理你想要的转换。

  • 如果你总是想看到一个searchBarscopeBar ,你可能不得不使用内置的scopeBar ,并用一个UISegmentedControl取代它,即使在search控制器没有激活的情况下,用户也会一直看到它。

更新:

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