How to dismiss the iOS Keyboard when the done button is pressed

It has puzzled many generations how to get rid of the keyboard when the user is done entering text into an iOS text field. There doesn’t seem to be an obvious action we can attach to make this happen.

iOS Simulator Screen shot 31 Dec 2013 05.45.27

That’s because rather than looking at the keyboard itself, we need to look at what actually brought it up in the first place: the UITextField. Even though the text field can trigger an action, we don’t want to touch that for dismissing the keyboard. All we need to do is to implement the following method from its delegate protocol:

This method is called whenever the return button is pressed. We return YES to agree, and resign the text field’s first responder status which takes the user focus away from it.

Since this is a protocol we *should* really conform to it formally by declaring it in the header file. It appears to work without this step, but let’s play it by the rules here:

Note that you need to connect your text field’s delegate in Interface Builder to the class that’s implementing the above method (i.e. self), otherwise the keyboard won’t be dismissed. To do this, control-drag from the text field to the orange square at the bottom of your view controller and select “delegate”. You can verify this in the connections inspector:

Screen Shot 2013-12-31 at 05.55.36

Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.

6 thoughts on “How to dismiss the iOS Keyboard when the done button is pressed

      1. I just watched the video and looking forward to trying it out when I get home. Just as an aside, I noticed that when I select the text field for the purpose of assigning a delegate, the selected text field is highlighted pink, not blue like in your video. I’m not sure if this is a clue leading to the source of my problem, but I thought I’d mention it anyway. Thanks for the video!

        1. Great, glad you like it! Pink is strange indeed – I can’t make Xcode show anything in pink. Let me know what you find out, it’s intriguing 😉

  1. Good news. I followed along with your video and it worked! I then went back to my code that wasn’t working. I think the problem was that I didn’t wait for the view controller to be highlighted when assigning it as delegate for the text field. After doing that, the keyboard successfully dismissed. Thanks for your help!

Add your voice!