I'm working on a project that have a UIViewController, on the view controller there is a UIScrollView and a UITextField on the scrollview.
like this:
I'm trying to dismiss the keyboard and hide it after typing some text in the textfield and tap anywhere outside the textfield.
I've tried the following code:
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self;
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
It works for me when I tap outside the scrollview, but when I tap on the scrollview nothing happens and the keyboard doesn't hide.
Is there any way to dismiss the keyboard when tapping anywhere outside the textfield?
thanks
Best Answer
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
orUITextField
Create an extension of the view controller. This has worked much smoother for me and with less hassle than trying to use
.resignFirstResponder()
Call
self.setupToHideKeyboardOnTapOnView()
in the viewDidLoad