Search code examples
iosuiviewcontrolleruisearchcontroller

How to dismiss a ViewController while the navigationItem's searchBar has focus


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.

  • On the first tap on the button, the searchBar loses its focus and the keyboard hides (as if [searchBar resignFirstResponder] had been called);
  • On the second tap, the view controller is finally being dismissed.

enter image description here

How can I make the first tap on the button dismiss the view controller immediately (removing the searchBar's focus as a side effect)?


Solution

  • 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];
    }