I have a few UITextFields
in static UITableVieweCells
, and I'm trying to dismiss keyboard when the user taps elsewhere. Here is my code:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
NSLog(@"touch began");
}
I didn't get any NSLogs
when I taped elsewhere. What am I doing wrong?`
I then tried self.view.userInteractionEnabled = YES;
, and self.tableView
, and they both didn't work.
Your touches are probably being swallowed by the table view cells. Try putting your keyboard dismiss code in tableView:didSelectRowAtIndexPath:
on your table view delegate instead.
EDIT:
Perhaps then you ought to use some combination of that and gesture recognizers:
UITapGestureRecognizer *navBarTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)];
[self.navigationController.navigationBar addGestureRecognizer:navBarTap];
UITapGestureRecognizer *tableViewTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)];
[self.tableView addGestureRecognizer:tableViewTap];