1

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() {
    super.viewDidLoad()


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

    view.addGestureRecognizer(tap)

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'.

1
  • Can you show your dismissKeyboard method code as well?
    – Zayne ZH
    Commented Sep 8, 2016 at 3:32

3 Answers 3

6

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
    view.endEditing(true)
   }

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: https://stackoverflow.com/a/5711504/6312593

2

You can try this one, its very simple solution, frequently used in swift to dismiss the keyboard.

Just add this function, that's it.

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) 
{
     self.view.endEditing(true)
}
1
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("dismiss:"))
view.addGestureRecognizer(tap)

func dismiss(gest : UITapGestureRecognizer){
        view.endEditing(true)
    }

This is working fine, try it.

Not the answer you're looking for? Browse other questions tagged or ask your own question.