Martheli
Martheli

Reputation: 981

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

Upvotes: 1

Views: 4033

Answers (3)

user5886755
user5886755

Reputation:

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)
}

Upvotes: 2

JFed
JFed

Reputation: 128

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

Upvotes: 6

Pavankumar
Pavankumar

Reputation: 288

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.

Upvotes: 1

Related Questions