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;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容