UISearchController introduced with iOS 8 and having problems getting it to display without a scope bar? There were some comments to my post on updating to the iOS 8 search controller that made me curious.
Creating the search bar
To recap, creating a
UISearchController with an associated
UISearchBar takes just a few lines of code. The following code snippet will create the controller and add the search bar to a table view header:
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil]; self.searchController.searchResultsUpdater = self; self.searchController.dimsBackgroundDuringPresentation = NO; self.tableView.tableHeaderView = self.searchController.searchBar; self.definesPresentationContext = YES;
If you want the search bar to also have a scope bar you would also include the titles and implement the
self.searchController.searchBar.scopeButtonTitles = @[NSLocalizedString(@"ScopeButtonCountry",@"Country"), NSLocalizedString(@"ScopeButtonCapital",@"Capital")]; self.searchController.searchBar.delegate = self;
Refer back to the original post for the full details.
Missing in Action
The curious problem happens when you do not want the scope bar. If you omit the extra two lines of code above which specify the titles and set the delegate the search bar is no longer visible. You can try this yourself with the World Facts sample code.
To figure out why the search bar is not visible we can use the view debugging capability of Xcode 6 (see WWDC 2014 session 413). Using the view debugger, you can see the search bar is added to the table view hierarchy:
The exploded visual view hierarchy is cool but it is difficult to spot the problem. In the screenshot below the search bar is actually the thin blue line towards the back.
With the UISearchBar selected the problem is revealed in the inspector which shows that it has a height of zero (which explains the thin blue line):
It seems there are situations where the UISearchBar is not automatically setting its size. There is some mention of the problem going back to iOS 8 betas in this Archived iOS 8 beta discussion. The solution is to force the search bar to set its frame once it has been added to the table view header:
For comparison the view in the debugger now looks as follows (with the UISearchBar highlighted with a height of 44):
Response From Apple
I created radar #20702394. The response from Apple was as follows:
-sizeToFit needs to be called on the searchBar, I believe this is part of our official sample code for adding a searchBar as the table header view.
If you are using
UISearchController you should call
sizeToFit on the