In, viewDidLoadmake your viewing controller listen for keyboard notifications and create a tap recognizer that will receive all events outside of your tableView:
- (void)viewDidLoad
{
[super viewDidLoad];
...
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(keyboardWillShow:) name:
UIKeyboardWillShowNotification object:nil];
[nc addObserver:self selector:@selector(keyboardWillHide:) name:
UIKeyboardWillHideNotification object:nil];
tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)];
...
}
Then, in the notification methods for the keyboard, add and remove the gesture recognizer from your view.
-(void)keyboardWillShow:(NSNotification *) note {
[self.view addGestureRecognizer:tapRecognizer];
}
-(void)keyboardWillHide:(NSNotification *) note
{
[self.view removeGestureRecognizer:tapRecognizer];
}
In the action method of your gesture recognizer, you leave all the first responders to remove the keyboard:
-(IBAction)dismissKeyboard:(id)sender
{
[self.view endEditing:TRUE];
}
Remember to end listening to keyboard notifications at some point:
[[NSNotificationCenter defaultCenter] removeObserver:self];
source
share