iPhone keyboard, Done button and resignFirstResponder iPhone keyboard, Done button and resignFirstResponder objective-c objective-c

iPhone keyboard, Done button and resignFirstResponder


I made a small test project with just a UITextField and this code

#import <UIKit/UIKit.h>@interface TextFieldTestViewController : UIViewController<UITextFieldDelegate>{    UITextField *textField;}@property (nonatomic, retain) IBOutlet UITextField *textField;@end#import "TextFieldTestViewController.h"@implementation TextFieldTestViewController@synthesize textField;- (void)viewDidLoad{    [self.textField setDelegate:self];    [self.textField setReturnKeyType:UIReturnKeyDone];    [self.textField addTarget:self                  action:@selector(textFieldFinished:)        forControlEvents:UIControlEventEditingDidEndOnExit];    [super viewDidLoad];}- (IBAction)textFieldFinished:(id)sender{    // [sender resignFirstResponder];}- (void)dealloc {    [super dealloc];}@end

The text field is an unmodified UITextField dragged onto the NIB, with the outlet connected.
After loading the app, clicking in the text field brings up the keyboard. Pressing the "Done" button makes the text field lose focus and animates out the keyboard. Note that the advice around the web is to always use [sender resignFirstResponder] but this works without it.


In Xcode 5.1

Enable Done Button

  • In Attributes Inspector for the UITextField in Storyboard find the field "Return Key" and select "Done"

Hide Keyboard when Done is pressed

  • In Storyboard make your ViewController the delegate for the UITextField
  • Add this method to your ViewController

    -(BOOL)textFieldShouldReturn:(UITextField *)textField{    [textField resignFirstResponder];    return YES;}


From the documentation (any version):

It is your application’s responsibility to dismiss the keyboard at the time of your choosing. You might dismiss the keyboard in response to a specific user action, such as the user tapping a particular button in your user interface. You might also configure your text field delegate to dismiss the keyboard when the user presses the “return” key on the keyboard itself. To dismiss the keyboard, send the resignFirstResponder message to the text field that is currently the first responder. Doing so causes the text field object to end the current editing session (with the delegate object’s consent) and hide the keyboard.

So, you have to send resignFirstResponder somehow. But there is a possibility that textfield loses focus another way during processing of textFieldShouldReturn: message. This also will cause keyboard to disappear.