How to hide (and show) the UISearchBar in a UITableView

- by

If you add a UISearchBar to your table view (see previous article) it’s just sitting there by default. Chances are you’d like to hide it when your table view first loads.

You can do this by adding the following code to your viewWillAppear method:

    - (void)viewWillAppear:(BOOL)animated {

    // scroll the search bar off-screen
    CGRect newBounds = self.tableView.bounds;
    newBounds.origin.y = newBounds.origin.y + self.searchBar.bounds.size.height;
    self.tableView.bounds = newBounds;

}

 

Now it’s hidden, users make a search, hit cancel… and then it comes back into view. Wouldn’t it be nice if we could hide it again after users are finished with their search? And sure we can! We’re already conforming to the UISearchBarDelegate protocol, so all we need to do is to implement the following method and react to the cancel button:

 

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {

    [self viewWillAppear:YES];

}

We could implement the same code as above, or just call the viewWillAppear method again.

Note that you have to set the search bar’s delegate to your class for this to work. Searches are working fine when it’s not set, but to react to the cancel button it needs to be set (either in code or via the Connections Inspector in Interface Builder).

You can find a full demo project on GitHub: Table Search 2013 (updated for iOS 7)



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.