iOS tutorial: hide keyboard after return / done key press in UITextField

When user finished editing text in UITextField it is good practice to hide keyboard after Done / Return key press. Another way of hiding keyboard is touch detected anywhere outside the UITextField. Both solutions are described below

1. Hide keyboard after Done / Return button press

To detect the confirm button press you need to implement UITextFieldDelegate protocol’s optional method textFieldShouldReturn:. So in header file add protocol declaration:

@interface MyViewController : UIViewController <UITextFieldDelegate>

Point the delegate that will handle protocol’s events in viewDidLoad():

self.playerNameField.delegate = self;

And in implementation file implement textFieldShouldReturn:

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    if (theTextField == self.playerNameField) {
        [theTextField resignFirstResponder];
    }
    return YES;
}

This will resignFirstResponder (means: hide keyboard) for playerNameField.

2. Hide keyboard after touch outside of UITextField

This is somehow separate to previous point, however also hides the keyboard when it is not needed. To do it you need to detect the touch on the screen. There is method in UIResponder that you should override to be notified about touch event:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //hides keyboard when another part of layout was touched
    [self.view endEditing:YES];
    [super touchesBegan:touches withEvent:event];
}

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!

5 thoughts on “iOS tutorial: hide keyboard after return / done key press in UITextField

Leave a reply to Emim Lumina Cancel reply