Switching between Text fields on pressing return key in Swift

前端 未结 15 1446
名媛妹妹
名媛妹妹 2020-12-04 09:25

I\'m designing an iOS app and I want that when the return key is pressed in my iPhone it directs me to the next following text field.

I have found a couple of similar

15条回答
  •  一向
    一向 (楼主)
    2020-12-04 09:53

    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
        }
      }
      

提交回复
热议问题