There are some answers out there such as this, but in the case where there is a UIScrollView
or UICollectionView
present, it doesn't work.
The touchesBegan
method on the viewController
will never get called.
On screen, I have a UITextField
at the top.
Below that, filling up the rest of the screen is a UICollectionView
.
I need to dismiss the keyboard if I touch anywhere besides the UITextField
(including the collection view obviously)
So what is the best way to do this?
For such a common UI paradigm it seems like there should be a well-known solution, but I've yet to come across it.
Drop in a UITextField (we will omit UITextView from now on, but it’s the same), start editing, and you will soon need to learn how to dismiss the keyboard. The code to dismiss is simple: The difficulty is where to put this code. There are 2 scenarios - using a scroll view, or not. 1. Using a scroll view
Hide the keyboard on tap outside : Keyboard handling is easy in React Native. It provides one module called Keyboard for keyboard related stuff. Just import that module and call it’s dismiss method to hide a keyboard.
We shall use 2 textView functions to control their behaviour: textViewDidBeginEditing (..) and textViewDidEndEditing (..). We shall separate the code of UITextFields and UITextView to make it easier to focus on each group keyboard control.
In the keyboard property, select “Dismiss on drag”. This will dismiss when you drag/scroll the scroll view. In using tap gesture recognizer, you might want to disable cancelsTouchesInView (set to NO), so that it pass the touch event to other views (eg table view cell).
To dismiss Keyboard on tap of the View: Add a Tap gesture to your ViewController.collectionView as follows:
//declare a property to store your current responder
@property (nonatomic, assign) id currentResponder;
//in viewDidLoad:
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignOnTap:)];
[singleTap setNumberOfTapsRequired:1];
[singleTap setNumberOfTouchesRequired:1];
[self.collectionView addGestureRecognizer:singleTap];
//Implement the below delegate method:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
self.currentResponder = textField;
}
//Implement resignOnTap:
- (void)resignOnTap:(id)sender {
[self.currentResponder resignFirstResponder];
}
The simple way to do it is:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With