IOS-手势指定响应区域

在开发过程中,我们可能会遇到这个问题. 当我们给一个view添加了手势,但是我们又不想点击view上面的视图也触发手势.如下图:
我们在红色view上添加了手势,但是又不想点击黄色view也触发.其实这里用到UITapGestureRecognizer的一个代理方法



上代码,先创建两个view,并且给bigView添加手势

    self.bigView = [[UIView alloc]initWithFrame:CGRectMake(50, 50, 100, 100)];
    self.bigView.backgroundColor = [UIColor redColor];
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bigMap:)];
    recognizer.delegate = self;
    [self.bigView addGestureRecognizer:recognizer];
    [self.view addSubview:self.bigView];
  
    self.smallView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    self.smallView.backgroundColor = [UIColor yellowColor];
    [self.bigView addSubview:self.smallView];

实现UITapGestureRecognizer的一个代理方法,我不用多说,大家一看就明白怎么回事了.这是就解决了防止点击黄色view也触发的问题了

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
    if ([touch.view isDescendantOfView:self.smallView]) {
        return NO;
    }
    return YES;
}

推荐阅读更多精彩内容