iPhone Development: Making the keyboard disappear after pressing “Done”

April 27, 2009 · 3 comments

in iPhone Development

iphone-keyboardWhile working on a new iPhone application the other day, I was surprised to find out that the keyboard does not automatically hide itself after pressing the “Done” button. This seems odd to me, because what would you want the “Done” button to do, other than hide the keyboard? It seems like this should be the default behavior, but unfortunately it isn’t. So if you want to automatically hide the iPhone’s keyboard when a user presses the “Done” button, here’s what you need to do.

In order to have the keyboard automatically hide itself when the “Done” button is pressed, you must implement the doneButtonOnKeyboardPressed event in the view controller. You don’t actually have to put any code inside of the event handler, simply having it present in your view controller is all that’s required. Here’s what the implementation looks like:

- (IBAction) doneButtonOnKeyboardPressed:(id)sender {
}

And that’s all there is to it! It seems like a very kludgy solution – why this isn’t the default behavior of the iPhone’s keyboard is beyond me. But it is what it is, and this is the solution.

{ 3 comments… read them below or add one }

Mk12 July 29, 2009 at 6:25 pm

There are also two other ways to do it:
1. Hook up the text field’s delegate with File’s Owner in IB, then in the view controller class (which is File’s Owner):
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[self resignFirstResponder];
return YES;
}
2. Make this action method:
- (IBAction)makeKeyboardGoAway {
[self resignFirstResponder];
}
then connect this to the text field’s Did End on Exit event in IB.

Mk12 July 29, 2009 at 6:28 pm

Sorry my comment above had a mistake here I corrected it:
1. Hook up the text field’s delegate with File’s Owner in IB, then in the view controller class (which is File’s Owner):
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[theTextField resignFirstResponder];
return YES;
}
2. Make this action method:
- (IBAction)makeKeyboardGoAway:(id)sender {
[sender resignFirstResponder];
}

Brandon July 29, 2009 at 9:39 pm

@Mk12, thanks for the tip, I’ll have to give that method a try!

Leave a Comment

Previous post:

Next post: