Dismissing the keyboard when a button is pressed, programmatically with swift?

后端 未结 4 1494
北恋
北恋 2021-02-15 00:07

How can I dismiss the keyboard when a button is pressed, programmatically with swift?

4条回答
  •  生来不讨喜
    2021-02-15 00:09

    It all depends on what triggered the keyboard to appear in the first place. If you have a UITextField on your page that brought it up, you can call textField.resignFirstResponder() to hide the keyboard again.

    If you used some other object to bring up the keyboard, simply take the reference of whatever you used and call resignFirstResponder() on that object.

    Example:

    Lets say you are using a button button1 to close the keyboard, and you have a textField1 that is triggering the keyboard.

    button1.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "buttonTapped"))
    

    Then in your buttonTappedFunction

    func buttonTapped(){
      textField1.resignFirstResponder()
    }
    

提交回复
热议问题