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

- by

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:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    // done button was pressed - dismiss keyboard
    [textField resignFirstResponder];
    return YES;
}

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:

@interface ViewController : UIViewController 

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



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

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

Leave a Reply to Jay VersluisCancel reply

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