Last active
November 17, 2017 09:04
-
-
Save asvdw/25fd8c5a4a63599205ac3f11336f574c to your computer and use it in GitHub Desktop.
iOS: Dismiss keyboard on click on view
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
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
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/