使用UIBarButtonItem将UISearchBar添加到UINavigationBar
在我的应用程序中,我曾经在表视图的标题视图中有一个搜索栏。 但是,我添加了一个搜索栏按钮项,当用户点击它时,我想要一个搜索栏在导航栏上设置动画,用户应该可以搜索。 这有点像Twitter iOS应用程序中的搜索栏。 这是我的UISearchController的代码:
self.searchController = ({ let controller = UISearchController(searchResultsController: nil) controller.searchResultsUpdater = self controller.hidesNavigationBarDuringPresentation = true controller.dimsBackgroundDuringPresentation = false controller.searchBar.sizeToFit() //self.tableView.tableHeaderView = controller.searchBar self.definesPresentationContext = true controller.searchBar.returnKeyType = .Search controller.searchBar.delegate = self return controller })()
以下是我的UINavigationBar现在的样子:
我该怎么做呢?
你快到了。 你需要做四件事:
- searchController.hidesNavigationBarDuringPresentation = false
- navigationItem.titleView = searchController.searchBar
- 隐藏导航栏中的所有当前UIBarButtonItem
- searchController.searchBar.becomesFirstResponder()
也就是说,您设置了UISearchController,因此它不会隐藏导航栏,因为UISearchBar将在那里显示。
然后,当您的IBAction运行时,您执行以下操作:
navigationItem.hidesBackButton = true navigationItem.titleView = searchController.searchBar navigationItem.rightBarButtonItem = nil searchController.searchBar.becomeFirstResponder()
这可以保证UISearchBar在成为第一个响应者时将使用整个UINavigationBar。 您还可以获得UISearchBar动画,该动画可以很好地隐藏UIBarButtonItems的非动画删除。
一旦用户完成搜索,您将需要实现UISearchBarDelegate(或者如果您更喜欢UISearchControllerDelegate)来恢复原始导航栏状态。
一个非常重要的细节是,为了使您的UISearchBar在titleView中可编辑,在推送您的时,不能使用definesPresentationContext = true设置其他视图控制器。