Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone keyboard, Done button and resignFirstResponder

This is probably a dumb question, but I can't find the answer in the docs. Did the "Done" button on the pop-up keyboard always cause the keyboard to disappear? I see a lot of code around the web like this:

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

When I press the "Done" button, the keyboard pops down and the UITextField resigns first responder.

I'm presuming that pressing the "Done" button didn't used to cause a UITextField to resignFirstResponder, but that behavior changed at some time.

I'm debugging on OS 3.0 - 3.1.3

like image 599
nevan king Avatar asked May 13 '10 17:05

nevan king


People also ask

How do you dismiss a keyboard in Swift?

Via Tap Gesture This is the quickest way to implement keyboard dismissal. Just set a Tap gesture on the main View and hook that gesture with a function which calls view. endEditing . Causes the view (or one of its embedded text fields) to resign the first responder status.


2 Answers

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.

like image 185
nevan king Avatar answered Sep 16 '22 21:09

nevan king


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; } 
like image 23
bickster Avatar answered Sep 20 '22 21:09

bickster