iOS app “next” key won't go to the next text f

2019-01-21 07:30发布

I have a simple scene (using storyboard in IB) with a Username and Password text box. I've set the keyboard to close when you are on the Password text field but can't get the next(return) button to work on the Username to switch the focus (or First Responder) to the Password text box.

I'm closing the keyboard while on the Password text field like this:

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
if (theTextField == self.textPassword) {
    [theTextField resignFirstResponder];
}
return YES;
}

I know it is something similar to this but just can't nail it down.

10条回答
叛逆
2楼-- · 2019-01-21 08:26

for those who want to use Swift language:

class MyClass: UIViewController, UITextFieldDelegate {

@IBOutlet weak var text1: UITextField!
@IBOutlet weak var text2: UITextField!
@IBOutlet weak var text3: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    text1.delegate = self
    text2.delegate = self
    text3.delegate = self


}

//....

func textFieldShouldReturn(textField: UITextField) -> Bool{
    if textField == self.text1 {
        self.text2.becomeFirstResponder()
    }else if textField == self.text2{
        self.text3.becomeFirstResponder()
    }else{
        self.text1.becomeFirstResponder()
    }
    return true
 }

 //...

}

:-)

查看更多
Animai°情兽
3楼-- · 2019-01-21 08:30

You have to add the UITextFieldDelegate in the header-file. Then you have to set

theTextField.delegate = self;

in the viewDidLoad-method. After that you can go on with

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    if (theTextField == self.textPassword) {
        [theTextField resignFirstResponder];
    } else if (theTextField == self.textUsername) {
        [self.textPassword becomeFirstResponder];
    }
    return YES;
}
查看更多
Rolldiameter
4楼-- · 2019-01-21 08:30

Here's what you would put:

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    if (theTextField == self.textPassword) {
        [theTextField resignFirstResponder];
    } else if (theTextField == self.usernameField) {
        [self.textPassword becomeFirstResponder];
    }
return YES;
}
查看更多
▲ chillily
5楼-- · 2019-01-21 08:32

I use this code that allows me to control the form behavior in the storyboard:

-(BOOL) textFieldShouldReturn:(UITextField *)textField{
    if(textField.returnKeyType==UIReturnKeyNext) {
        UIView *next = [[textField superview] viewWithTag:textField.tag+1];
        [next becomeFirstResponder];
    } else if (textField.returnKeyType==UIReturnKeyDone) {
        [textField resignFirstResponder];
    }
    return YES;
} 

All you need is to assign the order value as tag, and returnkey according to Next or Done on each input control.

查看更多
登录 后发表回答