iOS 嵌套UIScrollview的滑动冲突另一种解决方案

这篇文章主要是看了卓同学的嵌套UIScrollview的滑动冲突解决方案之后,我想换一种方式来实现,其实基本思想是一样的。

先说说整体结构:
一个mainScrollView上面有一个bannerViewsubScrollViewsubScrollView上面有三个tableView,基本就是微博个人主页的那种结构

基本思路:
mainScrollViewscrollEnabled设为NO
subScrollViewscrollEnabled设为YES(最开始也设为NO了,但是page的实现没有想到好的方法)
tableViewscrollEnabled设为NO
self.view上添加UIPanGestureRecognizer手势
这里我们还要用到UIDynamicAnimator添加惯性 & 弹性动画

这样实际上Pan手势和subScrollView上的手势会冲突,但是由于两个手势控制的方向是不一样的,Pan手势只控制垂直方向,而subScrollView上的手势控制水平方向,根据方向我们就可以解决手势冲突

解决手势冲突的代码

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
        UIPanGestureRecognizer *recognizer = (UIPanGestureRecognizer *)gestureRecognizer;
        CGFloat currentY = [recognizer translationInView:self.view].y;
        CGFloat currentX = [recognizer translationInView:self.view].x;
        //判断如果currentX为currentY的5倍及以上就是断定为横向滑动,返回YES,否则返货NO
        if (currentY == 0.0) {
            return YES;
        } else {
            if (fabs(currentX)/currentY >= 5.0) {
                return YES;
            } else {
                return NO;
            }
        }
    }
    return NO;
}

Pan手势的处理

关于Pan手势在UIGestureRecognizerStateChanged中我们获取到的是距离上一次移动的距离,因为我们每次方法结束时设置[recognizer setTranslation:CGPointZero inView:self.view],获取距离方便我们来设置contentOffset

我们在移动手势的时候改变contentOffset,还是根据关键点来判断是当前tableview滚动还是mainScrollView滚动,当手势结束之后我们添加惯性动画,使用UIDynamicItemBehavior来添加一个线速度,这个线速度就是手势的滑动速度

- (void)panGestureRecognizerAction:(UIPanGestureRecognizer *)recognizer {
    switch (recognizer.state) {
        case UIGestureRecognizerStateBegan:
            currentScorllY = self.mainScrollView.contentOffset.y;
            CGFloat currentY = [recognizer translationInView:self.view].y;
            CGFloat currentX = [recognizer translationInView:self.view].x;
            
            if (currentY == 0.0) {
                isVertical = NO;
            } else {
                if (fabs(currentX)/currentY >= 5.0) {
                    isVertical = NO;
                } else {
                    isVertical = YES;
                }
            }
            [self.animator removeAllBehaviors];
            break;
        case UIGestureRecognizerStateChanged:
        {
            //locationInView:获取到的是手指点击屏幕实时的坐标点;
            //translationInView:获取到的是手指移动后,在相对坐标中的偏移量
            
            if (isVertical) {
                //往上滑为负数,往下滑为正数
                CGFloat currentY = [recognizer translationInView:self.view].y;
                [self controlScrollForVertical:currentY AndState:UIGestureRecognizerStateChanged];
            }
        }
            break;
        case UIGestureRecognizerStateCancelled:
            
            break;
        case UIGestureRecognizerStateEnded:
        {
            
            if (isVertical) {
                //添加惯性方法
                self.dynamicItem.center = self.view.bounds.origin;
                //velocity是在手势结束的时候获取的竖直方向的手势速度
                CGPoint velocity = [recognizer velocityInView:self.view];
                UIDynamicItemBehavior *inertialBehavior = [[UIDynamicItemBehavior alloc] initWithItems:@[self.dynamicItem]];
                [inertialBehavior addLinearVelocity:CGPointMake(0, velocity.y) forItem:self.dynamicItem];
            
            
                // 通过尝试取2.0比较像系统的效果
                inertialBehavior.resistance = 2.0;
                __block CGPoint lastCenter = CGPointZero;
                __weak typeof(self) weakSelf = self;
               //在action进行contentOffset的赋值
                inertialBehavior.action = ^{
                    if (isVertical) {
                        //得到每次移动的距离
                        CGFloat currentY = weakSelf.dynamicItem.center.y - lastCenter.y;
                        [weakSelf controlScrollForVertical:currentY AndState:UIGestureRecognizerStateEnded];
                    }
                    lastCenter = weakSelf.dynamicItem.center;
                };
                [self.animator addBehavior:inertialBehavior];
                self.decelerationBehavior = inertialBehavior;
            }
        }
            break;
        default:
            break;
    }
    //保证每次只是移动的距离,不是从头一直移动的距离
    [recognizer setTranslation:CGPointZero inView:self.view];
}

contentOffset的设置

//控制上下滚动的方法
- (void)controlScrollForVertical:(CGFloat)detal AndState:(UIGestureRecognizerState)state {
    //判断是主ScrollView滚动还是子ScrollView滚动,detal为手指移动的距离
    if (self.mainScrollView.contentOffset.y >= maxOffsetY) {
        CGFloat offsetY = self.subTableView.contentOffset.y - detal;
        if (offsetY < 0) {
            //当子ScrollView的contentOffset小于0之后就不再移动子ScrollView,而要移动主ScrollView
            offsetY = 0;
            self.mainScrollView.contentOffset = CGPointMake(self.mainScrollView.frame.origin.x, self.mainScrollView.contentOffset.y - detal);
        } else if (offsetY > (self.subTableView.contentSize.height - self.subTableView.frame.size.height)) {
            //当子ScrollView的contentOffset大于contentSize.height时
            offsetY = self.subTableView.contentSize.height - self.subTableView.frame.size.height;
            CGRect frame = self.mainScrollView.frame;
            frame.origin.y += rubberBandDistance(detal, height);
            self.mainScrollView.frame = frame;
        }
        self.subTableView.contentOffset = CGPointMake(0, offsetY);
    } else {
        CGFloat mainOffsetY = self.mainScrollView.contentOffset.y - detal;
        if (mainOffsetY < 0) {
            //滚到顶部之后继续往上滚动需要乘以一个小于1的系数
            mainOffsetY = 0;
            CGRect frame = self.mainScrollView.frame;
            frame.origin.y += rubberBandDistance(detal, height);
            self.mainScrollView.frame = frame;
        } else if (mainOffsetY > maxOffsetY) {
            mainOffsetY = maxOffsetY;
        }
        self.mainScrollView.contentOffset = CGPointMake(self.mainScrollView.frame.origin.x, mainOffsetY);
        
        if (mainOffsetY == 0) {
            for (UITableView *tableView in tableArray) {
                tableView.contentOffset = CGPointMake(0, 0);
            }
        }
    }
    
    BOOL outsideFrame = self.mainScrollView.frame.origin.y > 64 || self.mainScrollView.frame.origin.y < 64;
    if (outsideFrame &&
        (self.decelerationBehavior && !self.springBehavior)) {
        
         //mainPosition为mainScrollView的初始化时的position
        CGPoint target = mainPosition;
        
        UIAttachmentBehavior *springBehavior = [[UIAttachmentBehavior alloc] initWithItem:self.mainScrollView attachedToAnchor:target];
        springBehavior.length = 0;
        springBehavior.damping = 1;
        springBehavior.frequency = 2;
        [self.animator addBehavior:springBehavior];
        self.springBehavior = springBehavior;
    }
}

这里弹性动画主要是靠当UIAttachmentBehavior,当mainScrollView.contentOffset.y < 0时我们就移动mainScrollView.frame,超过最大限度同理,这样的写法主要是为了实现弹性动画。

添加这两个动画之后基本上感到平顺很多

Demo在这里
参考
1.用UIKit Dynamics模仿UIScrollView
2.自定义UIScrollView

推荐阅读更多精彩内容