Martheli Martheli - 1 year ago 142
Swift Question

How to dismiss keyboard by tapping on screen

I am looking for a simple solution in swift to add the ability to tap anywhere on screen and dismiss the keyboard. I read a lot of answers on here but they all throw errors for me. The one I have used before is this:

override func viewDidLoad() {

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target:self, action: #selector(ViewController.dismissKeyboard))


This worked with one of my projects but it doesn't seem to work with any others. Whenever I try to add this to other projects I get error Type 'ViewController' has no member 'dismissKeyboard'.

Answer Source

You need to add a method above any reference to it. I put this code at the beginning of my files:

   func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status and drop into background

And then whenever I need to reference the .dismissKeyboard I use this inside the viewDidLoad():

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.dismissKeyboard))
    view.addGestureRecognizer(tap)  // Allows dismissal of keyboard on tap anywhere on screen besides the keyboard itself

And make sure to replace 'LoginViewController' with the current View Controller. As per your example, that is just 'ViewController'

If you are looking for a more in depth answer, see this by 7KV7:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download