Dismiss keyboard by touching background of UITableView Dismiss keyboard by touching background of UITableView ios ios

Dismiss keyboard by touching background of UITableView


This is easily done by creating a UITapGestureRecognizer object (by default this will detect a "gesture" on a single tap so no further customization is required), specifying a target/action for when the gesture is fired, and then attaching the gesture recognizer object to your table view.

E.g. Perhaps in your viewDidLoad method:

UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];[self.tableView addGestureRecognizer:gestureRecognizer];

And the hideKeyboard method might look like this:

- (void) hideKeyboard {    [textField1 resignFirstResponder];    [textField2 resignFirstResponder];    ...    ...}

Note that the gesture is not fired when touching inside a UITextField object. It is fired though on the UITableView background, footer view, header view and on UILabels inside cells etc.


The UITapGestureRecognizer solution works with table cell selection if you set:

gestureRecognizer.cancelsTouchesInView = NO;


Here is a best way to do this.Just do this

[self.view endEditing:YES];

or

[[self.tableView superView] endEditing:YES];