How to dismiss the keyboard from a UITextField in iOS

In this episode I’ll show you how to dismiss the iOS Keyboard, which is commonly brought up by a UITextField – but doesn’t want to leave easy once summoned.

It’s easy to overlook a step in this procedure, so I thought a screencast is in order. We’re discussing two dismissal options here:

  • when the DONE button is pressed
  • and when users tap outside the textfield

The latter option isn’t built into iOS, but users have come to rely on this behaviour. I’m using Xcode 5.1.1 and iOS 7.1 in this demo.

Happy hacking!

Steps in a nutshell

The trick is to implement a delegate method from the UITextField Protocol named textFieldShouldReturn. In it we need to tell the text field to resign its first responder status, giving up its “focus” so to speak.

Here’s the method:

We can use this method to utilise the actual text value of the input.

For this to work, the text field needs to know that your class is the delegate. Either hook it up to the orange square in Interface Builder and select delegate, or declare it in code:

To make the keyboard go away when someone taps outside of it, drag out a huge button over the area that is not covered by the keyboard. Hook it up to a method and simply call the textFieldShouldReturn method to it. Even as of iOS 11, that’s the only way to make it work.

Watch the full course in one convenient playlist:
Catch this episode on my iOS Dev Diary Podcast:

2 thoughts on “How to dismiss the keyboard from a UITextField in iOS

Leave a Reply

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