Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make return key on iPhone make keyboard disappear?

I have two UITextFields (e.g. username and password) but I cannot get rid of the keyboard when pressing the return key on the keyboard. How can I do this?

like image 832
K.Honda Avatar asked May 31 '11 15:05

K.Honda


People also ask

How do I get the return button on my Iphone keyboard?

Tap the “123” key in the bottom-left corner of the keyboard. 3. Find the Return button on the right side of the space bar, right below the Backspace key.

How do I dismiss the keyboard in iOS?

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

First you need to conform to the UITextFieldDelegate Protocol in your View/ViewController's header file like this:

@interface YourViewController : UIViewController <UITextFieldDelegate>

Then in your .m file you need to implement the following UITextFieldDelegate protocol method:

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

    return YES;
}

[textField resignFirstResponder]; makes sure the keyboard is dismissed.

Make sure you're setting your view/viewcontroller to be the UITextField's delegate after you init the textfield in the .m:

yourTextField = [[UITextField alloc] initWithFrame:yourFrame];
//....
//....
//Setting the textField's properties
//....    
//The next line is important!!
yourTextField.delegate = self; //self references the viewcontroller or view your textField is on
like image 124
Sid Avatar answered Oct 31 '22 23:10

Sid


Implement the UITextFieldDelegate method like this:

- (BOOL)textFieldShouldReturn:(UITextField *)aTextField
{
    [aTextField resignFirstResponder];
    return YES;
}
like image 43
Nick Weaver Avatar answered Oct 31 '22 23:10

Nick Weaver