Moving Onto The Next UITextField When 'Next' Is Tapped Moving Onto The Next UITextField When 'Next' Is Tapped xcode xcode

Moving Onto The Next UITextField When 'Next' Is Tapped


You need to make your view controller the UITextField delegate, and implement the UITextField delegate method:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {    if (textField == nameField) {        [textField resignFirstResponder];        [emailField becomeFirstResponder];    } else if (textField == emailField) {        // here you can define what happens        // when user presses return on the email field    }    return YES;}

Swift version:

func textFieldShouldReturn(textField: UITextField) -> Bool {    if textField == nameField {        textField.resignFirstResponder()        emailField.becomeFirstResponder()    } else if textField == emailField {        // here you can define what happens        // when user presses return on the email field    }    return true}

You may also want to scroll your view for the emailField to become visible. If your view controller is an instance of UITableViewController, this should happen automatically. If not, you should read this Apple document, especially Moving Content That Is Located Under the Keyboard part.


Additionally to @lawicko 's answer I often change the button text to give that final finishing touch (e.g. says next when there are more fields and then done when on the last):

- (void)textFieldDidBeginEditing:(UITextField *)textField{    BOOL isLastTextField = //.. your logic to figure out if the current text field is the last    if (isLastTextField) {        textField.returnKeyType = UIReturnKeyDone;    } else {        textField.returnKeyType = UIReturnKeyNext;    }}


Swift version of correct answer.

In my experience, you do not need to resignFirstResponder when switching textFields.

In this example, it's just your basic username and password textFields.

The keyboard "return key" in storyboard for username is set to "Next" and the one for password is set to "Done".

enter image description here

Then just connect the delegates for these two text fields and add this extension and you're pretty much done.

extension LoginViewController: UITextFieldDelegate {    func textFieldShouldReturn(textField: UITextField) -> Bool {        if textField == textFieldPassword {            self.view.endEditing(true)        } else {            textFieldPassword.becomeFirstResponder()        }        return true    }}