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
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.hideKeyboard()
in the viewDidLoadIntroduce a tap gesture recogniser and set and action for it.
Use the code:
nameofyourtextfield.resignfirstresponder()
swift 3
Go to Keyboard Type and Select Default or whatever you need the TextField for. Then override a method call it whatever you want i usually call it touchingBegins. Below is what you forgot to add
Details
xCode 8.2.1, Swift 3
Task
Set UITapGestureRecognizer for view of UIViewController which will close keyboard and make this functionality as Bool property of UIView.
Complex implementation but the usage is in one line
Usage
Full Sample
This works when touched outside input area for any number of input items.