How to make the keyboard disappear when click out of it? Swift

Asked

Viewed 2,115 times

1

I have a normal Textfield, but I’d like to know how to make the textField keyboard disappear when I click off it. I know how to make it disappear by clicking on Return using the delegate textFieldShouldReturn, but I wonder when I click out.

  • Would you like to make the keyboard or Textfield disappear? In the title you say the keyboard and in the question you say the Textfield.

  • Oops, truth Sorry for the confusion, I’ll tidy up

5 answers

3


A possible solution is to detect the click off the keyboard using a GestureRecognizer. Then call the method resignFirstResponder in the instance of textfield or call endEditing that forces any view descendant who is the first to respond to "waive" that condition.

class ViewController: UIViewController , UITextFieldDelegate {

    @IBOutlet var textField : UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        textField.delegate = self
        var tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
        view.addGestureRecognizer(tap)
    }

    func dismissKeyboard(){
        //textField.resignFirstResponder()
        view.endEditing(true)
    }
}
  • Dude, perfect! Thank you very much, keep helping us, :)

  • Great answer Rafael, but there are easier ways to accomplish. Check out my answer, only for learning purposes.

  • Thanks for the @Skal tip

1

Add the following method to Viewcontroller:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    super.touchesBegan(touches, withEvent: event)
    view.endEditing(true)
}
  • and how it can be added in delegate?

1

You can simply make the keyboard close as follows:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
     self.view.endEditing(true)
}

Only thing needed to work is to place textField as delegate of View

0

Exit the keyboard with click on the screen *Swift 4

override func viewDidLoad() {
    super.viewDidLoad()

    self.hideKeyboardWhenTappedAround()

    self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard)))
}

func hideKeyboardWhenTappedAround() {
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard))
    tap.cancelsTouchesInView = false
    view.addGestureRecognizer(tap)
}

@objc func dismissKeyboard() {
    self.view.endEditing(true)
}

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.