10

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

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Daniel Henneh
  • 301
  • 1
  • 2
  • 8
  • http://stackoverflow.com/questions/18756196/how-to-dismiss-keyboard-when-user-tap-other-area-outside-textfield in place of other area call it on button click – Deep Mehta Aug 11 '15 at 21:34

4 Answers4

29

There is also the so called "big hammer".

Just call self.view.endEditing(true)

The documentation states the following for this method:

Causes the view (or one of its embedded text fields) to resign the first responder status.

ullstrm
  • 9,812
  • 7
  • 52
  • 83
15

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()
}
Unome
  • 6,750
  • 7
  • 45
  • 87
2

you have to call resignFirstResponder on currently active UI Element (most likely, UITextField).

Trident
  • 810
  • 9
  • 20
2

Setting the UITextfield delegate programmatically swift 2.2 Add UITextFieldDelegate in your class.

https://stackoverflow.com/a/31689406/5576747

Community
  • 1
  • 1