Adding the fancy search magnifying glass to your UITableView

So you’re working on a search screen or popover with UITableViewController and you’re wondering how to get that fancy search magnifying glass in your search results, right?


In my example, I have my table view sourced by a simple array of data. This may not be the case for you, but you get the idea from the example. Simply add the constant UITableViewIndexSearch as the first section header title – UITableView will understand to replace the {search} text from that constant with the locale-specific image indicating search.

[array insertObject:UITableViewIndexSearch atIndex:0];
view raw gistfile1.m hosted with ❤ by GitHub

Then, you want to show the search bar when that icon is selected. Normal behavior when selecting an index in the right hand gutter is to scroll to that section header. The search magnifying glass, however, signifies the search bar section. The key is that you have to use a UISearchDisplayController and tell the table view to scroll up to the search bar’s rectangle:

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
if (index == 0) {
CGRect searchBarFrame = self.searchDisplayController.searchBar.frame;
[tableView scrollRectToVisible:searchBarFrame animated:NO];
return -1;
return index;
view raw gistfile1.m hosted with ❤ by GitHub

Pretty simple! This feature isn’t well documented in the Apple API but it’s quite handy for making your app feel native.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s