Switching between Text fields on pressing return key in Swift Switching between Text fields on pressing return key in Swift ios ios

Switching between Text fields on pressing return key in Swift


Make sure your UITextField delegates are set and the tags are incremented properly. This can also be done through the Interface Builder.

Here's a link to an Obj-C post I found: How to navigate through textfields (Next / Done Buttons)

class ViewController: UIViewController,UITextFieldDelegate {   // Link each UITextField (Not necessary if delegate and tag are set in Interface Builder)   @IBOutlet weak var someTextField: UITextField!   override func viewDidLoad() {      super.viewDidLoad()      // Do the next two lines for each UITextField here or in the Interface Builder      someTextField.delegate = self      someTextField.tag = 0 //Increment accordingly   }   func textFieldShouldReturn(_ textField: UITextField) -> Bool {      // Try to find next responder      if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {         nextField.becomeFirstResponder()      } else {         // Not found, so remove keyboard.         textField.resignFirstResponder()      }      // Do not add a line break      return false   }}


Swift 5

You can easily switch to another TextField when clicking return key in keyboard.

  • First, Your view controller conforms to UITextFieldDelegate and add the textFieldShouldReturn(_:) delegate method in ViewController
  • Drag from TextField to ViewController in Interface Builder. Then select the delegate option. Note : Do this for all TextField
  • Create an IBOutlet for all TextFields

    class ViewController: UIViewController, UITextFieldDelegate {  @IBOutlet weak var txtFieldName: UITextField!  @IBOutlet weak var txtFieldEmail: UITextField!  @IBOutlet weak var txtFieldPassword: UITextField!  func textFieldShouldReturn(_ textField: UITextField) -> Bool {    if textField == txtFieldName {       textField.resignFirstResponder()       txtFieldEmail.becomeFirstResponder()    } else if textField == txtFieldEmail {       textField.resignFirstResponder()       txtFieldPassword.becomeFirstResponder()    } else if textField == txtFieldPassword {       textField.resignFirstResponder()    }   return true  }}


I suggest that you should use switch statement in textFieldShouldReturn(_:).

// MARK: UITextFieldDelegatefunc textFieldShouldReturn(_ textField: UITextField) -> Bool {    switch textField {    case nameTextField:        phoneTextField.becomeFirstResponder()    case phoneTextField:        emailTextField.becomeFirstResponder()    case emailTextField:        descriptionTextField.becomeFirstResponder()    default:        textField.resignFirstResponder()    }    return false}