Dismiss iphone keyboard

Lounges picture Lounges · Dec 23, 2008 · Viewed 35.5k times · Source

I am trying to recreate something similar to the popup keyboard used in safari.

alt text

I am able to visually reproduce it by placeing a toolbar over my view and the appropriate buttons, however i cant figure out any way to dismiss the keyboard once the user has touched the done button.

Answer

Niels Hansen picture Niels Hansen · Jul 26, 2009

There is a couple of things you need to remember. The number #1 part developers forget to set is the delegate of the textField.

If you are using the Interface Builder, you must remember that you need to set the delegate of the textField to the file Owner.

If you are not using Interface Builder then make sure you set the delegate of the textfield to self. I also include the returnType. For Example if the textField was called gameField:

gameField.delegate = self;
gameField.returnKeyType = UIReturnKeyDone;

You must also implement the UITextFieldDelegate for your ViewController.

@interface YourViewController : UIViewController <UITextFieldDelegate> 

Finally you need to use the textFieldShouldReturn method and call [textField resignFirstResponder]

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

All your textFields will use this same method so you only need to have this setup once. As long as the delegate is set for the textField, the UITextFieldDelegate is implemented for the interface, you add the textFieldShouldReturn method and call the resignFirstResponder your set.