Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wszdwp/625a3f3c003c969e9e0e to your computer and use it in GitHub Desktop.
Save wszdwp/625a3f3c003c969e9e0e to your computer and use it in GitHub Desktop.
HideKeyBoard when tap outside of TextField or scroll a scrollView in Swift
/*
* For iOS 7 or later
* 1. In IB, set keyboard attr. to "Dismiss on drag"
* or in ViewDidLoad write
* self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
* https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIScrollView_Class/#//apple_ref/c/tdef/UIScrollViewKeyboardDismissMode
* 2. Add UITapGestureRecognizer in ViewDidLoad
*/
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Your init code here
// This only catch tapGesture outside of textField. keyboardDismissMode has to be set for scrolling(not tap) scrollView
var tapGesture = UITapGestureRecognizer(target:self, action: "hideKeyBoard")
tapGesture.cancelsTouchesInView = false
self.view.addGestureRecognizer(tapGesture)
}
func hideKeyBoard() {
self.myTextField.resignFirstResponder()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment