Switching between Text fields on pressing return key in Swift

前端 未结 15 1451
名媛妹妹
名媛妹妹 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:46

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

提交回复
热议问题