Search code examples
iosobjective-ccocoa-touchuisearchcontroller

Can't edit UISearchController UISearchBar in navigationItem titleView


When setting a UISearchController search bar in the navigationItem titleView, the search bar can't be edited.

In my viewDidLoad I am configuring a UISearchController.

self.searchViewController = [self.storyboard instantiateViewControllerWithIdentifier:NSStringFromClass([SearchViewController class])];
self.searchViewController.delegate = self;
self.searchController = [[UISearchController alloc] initWithSearchResultsController:self.searchViewController];
self.searchController.delegate = self;
self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.delegate = self;
self.navigationItem.titleView = self.searchController.searchBar;

I can't tap the search bar. The cursor does not appear and there is no user interaction.

Oddly, if I initialize the UISearchController locally without setting it to a property, then I can edit the search bar, just no delegate callbacks.

self.searchViewController = [self.storyboard instantiateViewControllerWithIdentifier:NSStringFromClass([SearchViewController class])];
self.searchViewController.delegate = self;
UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:self.searchViewController];
searchController.delegate = self;
searchController.searchResultsUpdater = self;
searchController.searchBar.delegate = self;
self.navigationItem.titleView = searchController.searchBar;

Another interesting behavior is that the clear button works (if some text is set in the search bar while initializing).


Solution

  • I am setting self.definesPresentationContext = YES; in the view controller that presents the view controller in question.

    This must be set to self.definesPresentationContext = NO; in viewWillAppear:.

    Now the search bar in the presented view controller can be edited.