Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dismiss the keyboard if a user taps off the on-screen keyboard?

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.

like image 873
Sheehan Alam Avatar asked Apr 19 '11 03:04

Sheehan Alam


People also ask

How do you dismiss a keyboard from the tap?

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.

How do you dismiss a keyboard on tap Flutter?

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.


2 Answers

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];     } } 
like image 111
visakh7 Avatar answered Oct 06 '22 03:10

visakh7


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.

like image 28
Taneem Tee Avatar answered Oct 06 '22 05:10

Taneem Tee