Edited for Swift 4
Edit: Added @objc
. While this isn't the best option for performance, one instance of it here shouldn't cause too many problems until there is a better solution.
Edited to fix when needing to interact with items behind GestureRecognizer.
Edit: Thanks @Rao for pointing this out. Added tap.cancelsTouchesInView = false
.
This should help you with having multiple UITextView
or UITextField
Create an extension of the view controller. This has worked much smoother for me and with less hassle than trying to use .resignFirstResponder()
extension UIViewController
{
func setupToHideKeyboardOnTapOnView()
{
let tap: UITapGestureRecognizer = UITapGestureRecognizer(
target: self,
action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard()
{
view.endEditing(true)
}
}
Call self.setupToHideKeyboardOnTapOnView()
in the viewDidLoad
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…