collectionView手势冲突

Q1: 给collectionView添加手势,子CollectionView的didSelect方法失效了

collectionViewA添加了 TapGesture,任意cellA内的collectionViewB点击事件回调didSelect不走了

问题代码

//点击collectionView 顶部空白区,则退出VC
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                              action:@selector(onTapGesture:)];
[collectionView addGestureRecognizer:tapGesture];

Solution

增加如下代码,解决

tapGesture.delegate = self;

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
  //未点击到cell时,响应添加到collectionView的手势
  if (touch.view == self.collectionView.backgroundView) {
      return YES;
  }
  //点击到cell时,就不响应collectionView的手势了。
  //这样,就会响应 cell内的点击事件,cell内的collectionView就走didSelect回调了。
  return NO;
}

Q2: 给collectionView的父视图添加手势,该CollectionView的didSelect方法失效了

Solution

```
  if (touch.view == 「想要响应的(内层)View」) {
  //禁止外层View手势响应,则回归到了 自身的响应
      return NO; 
  }
  return YES;
```

参考 collectionView手势与其它控件事件冲突问题

项目实践代码如下

containerView.delegate = self;

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
  
  if ([touch.view isDescendantOfView:self.collectionView]) {
      return NO;
  }

  return YES;
}

你可能感兴趣的:(collectionView手势冲突)