Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismiss keyboard by touching background of UITableView

I have a UITableView with UITextFields as cells. I would like to dismiss the keyboard when the background of the UITableView is touched. I'm trying to do this by creating a UIButton the size of the UITableView and placing it behind the UITableView. The only problem is the UIButton is catching all the touches even when the touch is on the UITableView. What am I doing wrong?

Thanks!

like image 556
Hua-Ying Avatar asked Feb 23 '10 19:02

Hua-Ying


1 Answers

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.

like image 148
mixja Avatar answered Sep 23 '22 17:09

mixja