Moving Onto The Next UITextField When 'Next' Is Tapped

I have an iPad application which has a sign up form within it. The form is very basic and contains only two UITextFields which are for Name & Email address.

The first TextField is for the candidates Name, When they enter their name in and press 'Next' on the keyboard I want this to automatically move to the next Email Address TextField to editing.

Any idea how I can set the next button the keyboard to jump to the next keyboard?

Thanks


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.


此外,以@lawicko的答案,我经常改变按钮上的文字以得到最后的点睛之笔(例如说, next当有更多的领域,然后done的时候就上):

- (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".

在这里输入图像描述

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
    }

}
链接地址: http://www.djcxy.com/p/73502.html

上一篇: 如何在UITextField返回键上添加一个操作?

下一篇: 点击“下一个”时移动到下一个UITextField