我们在项目中一般会用到textfield和tableview等,最近我遇到一个问题,当我们在写手势把键盘回收时,tableview的dissected...点击方法不会进去,查了下资料发现是因为手势的点击方法把我们tableview的点击方法拦截了,下面我教大家两种解决的办法
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(action_taskTap)];
tap.delegate = self;
[self.view addGestureRecognizer:tap];
下面我们重写手势方法:- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
NSLog(@"%@",NSStringFromClass([touch.view class]));
if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//如果是点击的是tableview,return NO
return NO;
}
return YES;
}
- (void)action_taskTap{
[self.view endEditing:YES];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];弹出
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];收回
- (void)keyboardWillShow:(NSNotification *)notice {
在弹出键盘的通知方法里面我们添加一个背景我淡黑的透明view,然后在view上面加上一个手势
self.keyView = [[UIView alloc]initWithFrame:self.view.frame];
self.keyView.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.3];
[self.view addSubview:self.keyView];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(action_sendTap)];
tap.delegate = self;
[self.keyView addGestureRecognizer:tap];
}
实现手势方法
- (void)action_sendTap{
for (UIView *view in self.view.subviews) {
[view endEditing:YES];
}
}
- (void)keyboardWillHide:(NSNotification *)notice {
移除这个view
[self.keyView removeFromSuperview];
}