Search bar not showing without a scope bar

Using the 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.

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 UISearchBarDelegate:

self.searchController.searchBar.scopeButtonTitles = @[NSLocalizedString(@"ScopeButtonCountry",@"Country"),
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:

[self.searchController.searchBar sizeToFit];

For comparison the view in the debugger now looks as follows (with the UISearchBar highlighted with a height of 44):


I created radar #20702394 if you want to duplicate. I will update this post if I get a response from Apple. In the meantime, if you are using UISearchController you may want to try calling sizeToFit on the UISearchBar if you are having layout problems.

Never Miss A Post

Sign up to get my iOS posts and news direct to your inbox and I'll also send you a PDF of my WWDC Viewing Guide

    Unsubscribe at any time. See privacy policy.

    Archives Categories