I updated my app to handle the new iOS 11 search behavior for search bars under the navigation bar:
- (void)viewDidLoad
{
[super viewDidLoad];
UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.navigationItem.searchController = searchController;
// Those are optional, but that's what I want my UI to look like
searchController.hidesNavigationBarDuringPresentation = NO;
searchController.obscuresBackgroundDuringPresentation = NO;
self.navigationItem.hidesSearchBarWhenScrolling = NO;
}
I also have a button on my view, which when tapped will dismiss the current view controller:
- (IBAction)dismiss:(id)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
The problem is: if the searchController's searchBar has focus (ie. is the first responder) when the user taps the button, the view controller is not dismissed.
[searchBar resignFirstResponder]
had been called);How can I make the first tap on the button dismiss the view controller immediately (removing the searchBar's focus as a side effect)?
The solution to dismiss the view controller immediately is to use the UISearchController
isActive
property:
- (IBAction)dismiss:(id)sender
{
self.navigationItem.searchController.active = NO;
[self dismissViewControllerAnimated:YES completion:nil];
}