ScrollView嵌套tableview或者collectionView手势冲突

5,188 阅读1分钟

目的

开发过程中,遇到背景是大的scrollview,我们称为mainScollview。里面嵌套tableview或者collectionview.我们称为subScrollView 类似于这样 滑动页面,mainScrollView先滚动,滚到顶部,中间tab吸顶,subScrollView再滚动。

难点

屏幕接触滑动手势,需要判断哪个scrollview响应滑动事件。那么久需要解决手势冲突。

  1. 对mainScrollview和subScrollView设置同时识别多个手势

/**
 同时识别多个手势

 @param gestureRecognizer gestureRecognizer description
 @param otherGestureRecognizer otherGestureRecognizer description
 @return return value description
 */
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}
  1. 通过偏移量设置响应的scrollview
//WBShopBackScrollView 为mainScollview. WBShopCenterCollectionView 为subScrollview
//isMainScrollCanScroll 为mainscrollview是否可滑动。
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([scrollView isKindOfClass:[WBShopBackScrollView class]]) {
        CGFloat bottomCellOffset = self.maxOffsetHeight;
        if (scrollView.contentOffset.y >= bottomCellOffset) {//滑动到顶部了
            //保持在顶部不动
            scrollView.contentOffset = CGPointMake(0, bottomCellOffset);
            if (self.isMainScrollCanScroll) {
                self.isMainScrollCanScroll = NO;
            }
        }else{
                    //当向上mainScrollview滑动的时候,不走。当到达顶部,isMainScrollCanScroll为no的时候,mainScrollView待在顶部,除非subScrollview复位,恢复isMainScrollCanScroll为yes时,恢复mainSCrollview的滑动。

            if (!self.isMainScrollCanScroll) {//子视图没到顶部
                scrollView.contentOffset = CGPointMake(0, bottomCellOffset);
            }
        }
    }else if ([scrollView isKindOfClass:[WBShopCenterCollectionView class]]){
         if (self.isMainScrollCanScroll) {
                scrollView.contentOffset = CGPointZero;
            }
            //向下拉取,
            if (scrollView.contentOffset.y <= 0) {
                self.isMainScrollCanScroll = YES;
                scrollView.contentOffset = CGPointZero;
            }
    }
}

最后

这个使用场景比较简单,subScrollview是单个的collectionview.如果遇到底部subScrollview可以左右滑动。参考下面的demo 简书简介 githubDemo