@holger's answer helps me fix my problem in iOS 10 - which it accidentally hide the whole navigation bar when pressing CANCEL.
Since my app has a logo sitting at the title of navigation bar, the search bar has to be hidden when not in use. So I added a search button as rightBarButtonItem
, and trigger @holger's code when pressed.
@IBAction func onSearchAction(_ sender: UIBarButtonItem) {
if #available(iOS 11.0, *) {
navigationItem.searchController = searchController
} else {
// Fallback on earlier versions
searchController.hidesNavigationBarDuringPresentation = false
tableView.tableHeaderView = searchController.searchBar
}
searchController.isActive = true
}
func didPresentSearchController(_ searchController: UISearchController) {
asyncAfter(.milliseconds(300)) {
searchController.searchBar.becomeFirstResponder()
}
}
By referring to another answer here, I added becomeFirstResponder()
inside didPresentSearchController
with a slight delay. So the keyboard will appears without tapping. Finally, implements UISearchControllerDelegate
so that it will disappears when cancelled:
func willDismissSearchController(_ searchController: UISearchController) {
if #available(iOS 11.0, *) {
navigationItem.searchController = nil
} else {
// Fallback on earlier versions
tableView.tableHeaderView = nil
}
}