I'm wondering how to make the keyboard disappear when the user touches outside of a UITextField
.
相关问题
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
- “Zero out” sensitive String data in Swift
- Get the NSRange for the visible text after scroll
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- Xcode: Is there a way to change line spacing (UI L
- Swift - hide pickerView after value selected
- How do you detect key up / key down events from a
- didBeginContact:(SKPhysicsContact *)contact not in
I think the easiest (and best) way to do this is to subclass your global view and use
hitTest:withEvent
method to listen to any touch. Touches on keyboard aren't registered, so hitTest:withEvent is only called when you touch/scroll/swipe/pinch... somewhere else, then call[self endEditing:YES]
.This is better than using
touchesBegan
becausetouchesBegan
are not called if you click on a button on top of the view. It is better thanUITapGestureRecognizer
which can't recognize a scrolling gesture for example. It is also better than using a dim screen because in a complexe and dynamic user interface, you can't put dim screen everywhere. Moreover, it doesn't block other actions, you don't need to tap twice to select a button outside (like in the case of aUIPopover
).Also, it's better than calling
[textField resignFirstResponder]
, because you may have many text fields on screen, so this works for all of them.Swift 4 oneliner
In this case, there can be use ScrollView and added to
TextField
in ScrollView and I want Tap theScrollView
and View then Dismiss the Keyboard. I tried to create sample code just in case. Like this,Your Storyboard Look at that Just Like.
I tried many of the responses here and had no luck. My tap gesture recognizer was always causing my UIButtons to not respond when tapped, even when I set the cancelsTouchesInView property of the gesture recognizer to NO.
This is what eventually solved the issue:
Have an ivar:
When a text field begins editing, set the gesture recognizer:
Then the trick is in how you set up the dismissKeyboard method:
I guess there's just something about getting the dismissKeyboardSelector execution out of the touch handling execution stack...
You'll need to add an
UITapGestureRecogniser
and assign it to the view, and then call resign first responder on theUITextField
on it's selector.The code:
In viewDidLoad
In dismissKeyboard:
(Where
aTextField
is the textfield that is responsible for the keyboard)Swift 3 version looks like that
For dismissKeyboard