How to resign first responder from text field when user tap elsewhere? How to resign first responder from text field when user tap elsewhere? ios ios

How to resign first responder from text field when user tap elsewhere?


I found the answer here:

If your ultimate aim is just to resign the first responder, thisshould work: [self.view endEditing:YES]

The endEditing(_:) method is designed right for it

Causes the view (or one of its embedded text fields) to resign the first responder status.


For a more robust and clean solution add a tap gesture recognizer to your primary view.

This will work better with nested views and will be cleaner than secret buttons in code and UI builder.

In your view did load:

UITapGestureRecognizer* tapBackground = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)];[tapBackground setNumberOfTapsRequired:1];[self.view addGestureRecognizer:tapBackground];

..and define your target action to be triggered on tap:

-(void) dismissKeyboard:(id)sender{    [self.view endEditing:YES];}


The best option is the shortest way ;)

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    [self.view endEditing:YES];}