How to programmatically dismiss a UISearchBar?

This is a sorta old question, but I just beat my head against this for an hour or two and finally figured it out, so I thought I’d share for posterity. At first I tried doing things like resigning first responder / deleting search text / etc by hand, but in this view I wanted the user to be able to possibly use the search bar multiple times, and doing things manually was meaning that the search bar would have had to be re-set-up every time the user started editing it again – seemed like the wrong approach. Here’s what I did:

I had already added the search bar, with the optional search display controller, in Interface Builder. In my implementation, I set up a UISearchDisplayController IBOutlet, and then linked it to the search display controller using IB. Finally, in the spot where I want to dismiss the search bar, I simply have to call:

[mySearchController setActive:NO];

Works like a charm!

Leave a Comment