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

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:

 

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:

 

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)

About Jay Versluis

Jay is a medical miracle known as a Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Add your voice!