Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen for UIReturnKeyType.Next with Swift iOS

Tags:

xcode

ios

swift

When the user presses next on the keypad I want to move from the current UITextField to the next UITextField, the UIReturnKeyType is set to UIReturnKeyType.Next

Here is how I have the UITextField set up.

username.returnKeyType = UIReturnKeyType.Next
username.textColor = UIColor.whiteColor()
username.placeholder = "Username"
username.borderStyle = UITextBorderStyle.RoundedRect
uUsername.textAlignment = NSTextAlignment.Center
username.backgroundColor = UIColor.lightGrayColor()
username.font = UIFont(name: "Avenir Next", size: 14)
username.autocapitalizationType = UITextAutocapitalizationType.None
username.autocorrectionType = UITextAutocorrectionType.No
like image 983
Stephen Fox Avatar asked Nov 28 '22 17:11

Stephen Fox


1 Answers

You have to configure the UITextFieldDelegate method textFieldShouldReturn:. From within this method, you can check which text field is returning and reassign first responder status accordingly. Of course this mean you'll have to assign your class as the delegate of the text fields.

Example:

class MyClass: UITextFieldDelegate {

    func setup() { // meaningless method name
        textField1.delegate = self
        textField2.delegate = self
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        if (textField === textField1) {
            textField2.becomeFirstResponder()
        } else if (textField === textField2) {
            textField2.resignFirstResponder()
        } else {
            // etc
        }

        return true
    }
}
like image 149
Mick MacCallum Avatar answered Dec 05 '22 14:12

Mick MacCallum