Dismiss the Keyboard When Clicking the UISearchBar Search Button in MonoTouch

Like me, if you’re new to MonoTouch and iOS and you’re coming from a long period in Visual Studio then things are different. If you’ve found this blog post then you know what I mean.

If you’re implementing a simple search pattern where ViewController A contains UISearchBar and pushes to ViewController B to display search results when UISearchBar Search Button is Clicked you’ll want to dismiss the keyboard or it’ll still appear when navigating back to ViewController A and annoyingly won’t go away. Your users won’t appreciate that.

To test an API that Developers on my Team at work are building I decided to build an iPhone App as the front end where I’ll implement all of the API functionality. These are screenshots from that application:

View Controller with UISearchBar

 

The Keyboard will appear at runtime when typing into the UISearchBar:

 

My UISearchBar Outlet is defined in XCode Interface Builder as txtSearch:

To dismiss the Search Button you’ll need to register it in ViewController A in ViewDidLoad():

 

That’s all you need to do.