I want to be able to dismiss the iPhone keyboard when the user taps anywhere outside of the keyboard. How can I go about doing this? I know I need to dismiss the responder, but need to know how to implement it when a user taps out of the keyboard space.
Android devices have a solution; press the physical back button (provided on some mobile phones) or the soft key back button, and it closes the keyboard.
TextField is a very common widget in Flutter. When you click on the TextField it opens up the on-screen keyboard. To hide/dismiss the keyboard you have to press the back button in Android and the done button (inside the onscreen keyboard) in iOS.
You'll need to add an UITapGestureRecogniser
and assign it to the view, and then call resign first responder on the textfield on it's selector.
The code:
In viewDidLoad
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)]; [self.view addGestureRecognizer:tap];
In dismissKeyboard:
-(void)dismissKeyboard { [aTextField resignFirstResponder]; }
(Where aTextField is the textfield that is responsible for the keyboard)
OPTION 2
If you can't afford to add a gestureRecognizer then you can try this
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch * touch = [touches anyObject]; if(touch.phase == UITouchPhaseBegan) { [aTextField resignFirstResponder]; } }
The simplest solution I have used is this:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self.view endEditing:YES]; }
The endEditing command can be used on any view that contains your textfield as a subview. The other advantage of this method is that you don't need to know which textfield triggered the keyboard. So even if you have a multiple textfields, just add this line to the superview.
Based on the Apple documentation, I think this method exists specifically to solve this problem.
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