iOS子view不继承父view的响应
2018-07-25 本文已影响0人
MichealXXX
现在很多时候我们都需要通过给view添加UITapGestureRecognizer来实现交互,但是如果在这个view上添加了子view也会自动继承手势,如果我们不希望子view继承父view的事件响应这时候就需要通过UITapGestureRecognizer的代理方法来实现了。
首先我们用代码创建一个view并且给它添加一个手势
UIView *firstView = [[UIView alloc] init];
firstView.userInteractionEnabled = YES;
[self.view addSubview:firstView];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TapAction)];
//记得添加代理
tap.delegate = self;
[firstView addGestureRecognizer:tap];
在firstView上再次添加一个view,叫做secondView好了
UIView * secondView = [[UIView alloc] init];
secondView.userInteractionEnabled = YES;
[firstView addSubview: secondView];
然后在interface中声明代理
<UIGestureRecognizerDelegate>
实现其代理方法
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
if ([touch.view isDescendantOfView: secondView]) {
return NO;
}
return YES;
}