Skip to content

Instantly share code, notes, and snippets.

@asvdw
Last active November 17, 2017 09:04
Show Gist options
  • Save asvdw/25fd8c5a4a63599205ac3f11336f574c to your computer and use it in GitHub Desktop.
Save asvdw/25fd8c5a4a63599205ac3f11336f574c to your computer and use it in GitHub Desktop.
iOS: Dismiss keyboard on click on view
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:
#selector(ViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Dismiss Keyboard
func dismissKeyboard(){
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
}
@asvdw
Copy link
Author

asvdw commented Apr 11, 2016

Using #selector will check your code at compile time to make sure the method you want to call actually exists. Even better, if the method doesn’t exist, you’ll get a compile error: Xcode will refuse to build your app, thus banishing to oblivion another possible source of bugs.
Source: https://swift.org/blog/swift-2-2-new-features/

@DamonChen117
Copy link

Add
tap.cancelsTouchesInView = false
to prevent it affecting other GestureRecognizers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment