Switching between Text fields on pressing return key in Swift

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

    No any special, here is my currently using to change the textFiled. So the code in ViewController looks good :). #Swift4

    final class SomeTextFiled: UITextField {
    
      public var actionKeyboardReturn: (() -> ())?
    
      override init(frame: CGRect) {
          super.init(frame: frame)
          super.delegate = self
      }
    
      required init?(coder aDecoder: NSCoder) {
          super.init(coder: aDecoder)
          fatalError("init(coder:) has not been implemented")
      }
    
      func textFieldShouldReturn(_ textField: UITextField) -> Bool {
          self.resignFirstResponder()
          actionKeyboardReturn?()
          return true
       }
    }
    
    extension SomeTextFiled: UITextFieldDelegate {}
    
    
    class MyViewController : UIViewController {
    
        var tfName: SomeTextFiled!
        var tfEmail: SomeTextFiled!
        var tfPassword: SomeTextFiled!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            tfName = SomeTextFiled(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
            tfName.actionKeyboardReturn = { [weak self] in
                self?.tfEmail.becomeFirstResponder()
            }
            tfEmail = SomeTextFiled(frame: CGRect(x: 100, y: 0, width: 100, height: 100))
            tfEmail.actionKeyboardReturn = { [weak self] in
                self?.tfPassword.becomeFirstResponder()
            }
            tfPassword = SomeTextFiled(frame: CGRect(x: 200, y: 0, width: 100, height: 100))
            tfPassword.actionKeyboardReturn = {
                /// Do some further code
            }
        }
    }
    

提交回复
热议问题