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

2 02 2013

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!



4 responses

21 05 2013

I had to add some code in the viewDidLoad method

self.playerNameField.delegate = self;

in order to get textFieldShouldReturn called

25 05 2013
Jacek Milewski

yes, you’re right. Thank you!

I’ve added your feedback to the post

26 05 2014
IOS编程101:关闭输入键盘 | 进步博客

[…] 1.iOS tutorial: hide keyboard after return / done key press in UITextField […]

26 06 2014
Emim Lumina

I Geek,
I need a idea about both Return & Done buttons. Any idea?

Thanks in advance!

Give Your feedback:

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: