Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 928
kylesyoon Avatar asked Dec 02 '22 15:12

kylesyoon


2 Answers

I had the same issue.

Imagine you have FirstViewController and SecondViewController, and booth have a UISearchBar on the titleView.

To fix the problem I had this code to booth UIViewController's.

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    self.definesPresentationContext = true

}

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)

    self.definesPresentationContext = false

} 
like image 152
Bruno Coelho Avatar answered May 30 '23 11:05

Bruno Coelho


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.

like image 43
kylesyoon Avatar answered May 30 '23 11:05

kylesyoon