点击其他任何地方,收回键盘
基本思想如下:
1. 在ViewController载入的时候,将键盘显示和消失的Notification添加到self.view里。
2. 分别在键盘显示和消失时添加和删除TapGestureRecognizer
示例代码如下:
UIViewController的源代码里:
{
[super viewDidLoad];
[self setUpForDismissKeyboard];
}
- (void)setUpForDismissKeyboard {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
UITapGestureRecognizer *singleTapGR =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(tapAnywhereToDismissKeyboard:)];
NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
[nc addObserverForName:UIKeyboardWillShowNotification
object:nil
queue:mainQuene
usingBlock:^(NSNotification *note){
[self.view addGestureRecognizer:singleTapGR];//键盘出现的时候添加点击手势监听
}];
[nc addObserverForName:UIKeyboardWillHideNotification
object:nil
queue:mainQuene
usingBlock:^(NSNotification *note){
[self.view removeGestureRecognizer:singleTapGR];//键盘退下的时候删除点击手势监听
}];
}
- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
//此method会将self.view里所有的subview的first responder都resign掉
[self.view endEditing:YES];
}