用UIBarButtonItem将UISearchBar添加到UINavigationBar
问题描述:
在我的应用程序中,我曾经在我的表视图的标题视图中有一个搜索栏。但是,我添加了一个搜索栏按钮项目,当用户点击它时,我需要一个搜索栏在导航栏上进行动画制作,并且用户应该能够搜索。这有点像Twitter iOS应用中的搜索栏。这里是我的UISearchController代码:用UIBarButtonItem将UISearchBar添加到UINavigationBar
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
})()
我怎么会去这样做呢?
答
你快到了。你需要做四件事情:
- searchController.hidesNavigationBarDuringPresentation =假
- navigationItem.titleView = searchController.searchBar
- 隐藏所有你在导航栏中
- searchController.searchBar.becomesFirstResponder具有当前UIBarButtonItems ()
也就是说,您设置了您的UISearchController,因此它不会隐藏导航栏,因为将显示UISearchBar t这里。
然后,当你的IBAction为运行时,你做这样的事情:
navigationItem.hidesBackButton = true
navigationItem.titleView = searchController.searchBar
navigationItem.rightBarButtonItem = nil
searchController.searchBar.becomeFirstResponder()
这保证当它成为第一个响应者的UISearchBar将使用整个UINavigationBar的。您还可以获得UISearchBar动画,该动画在隐藏对UIBarButtonItems的无生气删除方面做得很好。
用户完成搜索后,您需要实现UISearchBarDelegate(或者如果您更喜欢UISearchControllerDelegate)才能恢复原始导航栏状态。
一个非常重要的细节是,为了让您的UISearchBar在titleView中可编辑,在推送您的时候,不能使用definePresentationContext = true设置其他视图控制器。
我正是在这里回答这个问题http://stackoverflow.com/questions/32259863/ios-search-bar-in-navigation-bar/32260397#32260397 –
@VictorSigler,我看着你的答案类似的问题。我真的希望我的搜索栏出现在与uibarbuttonitem相同的视图控制器中。那么,我如何在IBAction中做到这一点?我试图通过将导航栏的titleView设置为barbuttonitem方法中的搜索栏来完成此操作,但它不起作用。 –