0

I have an Text Field in my layout, which gets filled out, and afterwards when clicking on the UIButton in the layout, I want to hide the virtual keyboard.

I assume this can be done easily?

Gucci
  • 921
  • 1
  • 7
  • 27
  • yourTextBox.resignFirstResponder() – bseh Jul 12 '18 at 11:40
  • Possible duplicate of [How to dismiss keyboard iOS programmatically when pressing return](https://stackoverflow.com/questions/18755410/how-to-dismiss-keyboard-ios-programmatically-when-pressing-return) – mag_zbc Jul 12 '18 at 11:47
  • 1
    _where can I find an example of it?_ - literally in the first link that appears on Google after typing `iOS hide keyboard` – mag_zbc Jul 12 '18 at 11:48
  • @mag_zbc Im using a UIButton for dismissing the keyboard not the return key. – Gucci Jul 12 '18 at 11:54
  • Dismissing keyboard works the same way, wherever you want to call it from – mag_zbc Jul 12 '18 at 11:56
  • Make an outlet of your textField and add an action for the button for event touchupinside. See the apple docs how to create outlets and add actions. When the button is pressed the action method will be triggered, call self.textField.resignFirstResponder() or self.view.endEditing(true) – Umair Jul 12 '18 at 11:57

3 Answers3

4

You can put below line in button click action.

self.view.endEditing(true)
Nishu_Priya
  • 1,251
  • 1
  • 10
  • 23
2
extension UIViewController {
func hideKeyboardWhenTappedAround() {
    let tap: UITapGestureRecognizer =
        UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
    view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
    view.endEditing(true)
}

}

Use this Extension.

You can hide the Keyboard by tapping anywhere on the screen or just call dissmissKeyboard() to hide it.

Fabian Gr
  • 215
  • 1
  • 12
-2

text box means UITextView? if it is UITextView then resignFirstResponder() is not allowed

you have to hide keyboards by clicking on background view