给View添加手势,防止点击View上其他视图触发点击效果

  • 在开发过程中,我们可能会遇到这个问题. 当我们给一个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];
    
  • 接着,在手势代理方法UIGestureRecognizerDelegate

      // 拦截点击事件,只让添加了手势的view响应事件
      - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
      	if ([touch.view isDescendantOfView:self.smallView]) {
      		return NO;
      	}
      	return YES;
      }
    
  • OK,处理完成.

posted on 2017-04-25 10:18  小北在行走  阅读(633)  评论(0编辑  收藏  举报

导航