How to make the keyboard disappear when clicking outside of it? Swift

1

I have a normal TextField, but I would like to know how to make the textField keyboard disappear when I click outside it. I know to make it disappear by clicking return using the textFieldShouldReturn delegate, but I would like to know when I click outside.

    
asked by anonymous 29.07.2015 / 18:39

5 answers

3

One possible solution is to detect the click off the keyboard using a GestureRecognizer . Then call the resignFirstResponder method on the textfield instance or call endEditing which forces any descendant of the view to be the first to "give up" this 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)
    }
}
    
30.07.2015 / 00:55
1

Add the following method to the ViewController :

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    super.touchesBegan(touches, withEvent: event)
    view.endEditing(true)
}
    
03.08.2015 / 04:28
1

You can simply have 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 put the textField as a delegate of View

    
08.08.2015 / 22:01
0

You can use the touchesBegan method ( link ).

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    textField.resignFirstResponder()
}

Add your text field in the code above.

    
04.09.2018 / 23:03
0

Exit the keyboard by clicking the * Swift 4 screen

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)
}
    
10.10.2018 / 19:26