Skip to content

Instantly share code, notes, and snippets.

@wszdwp wszdwp/HideKeyBoard.swift
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.