控制UIScrollView滑动方向解决方案

需求:取消UIScrollView顶部下拉的弹簧效果,并且当滑动到顶部时scrollView禁止滑动,其他状态下可支持自由滑动。

借助UIPanGestureRecognizer可以实现这个控制UIScrollView的滑动方向的需求。

@interface MyScrollView : UIView 
@property (nonatomic, strong) UIScrollView *scrollView;
@end
@implementation MyScrollView
- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        self.scrollView = [[UIScrollView alloc]init];
        //  去除UIScrollView150ms的延迟响应时间
        self.scrollView.delaysContentTouches = NO;
        [self addSubview:self.scrollView];
        
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
        pan.delegate = self;
        [self addGestureRecognizer:pan];
    }
    return self;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    self.scrollView.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
}
- (void)handlePan:(UIPanGestureRecognizer *)pan {
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
  return YES;
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) {

        UIPanGestureRecognizer *pan = (UIPanGestureRecognizer *)gestureRecognizer;
        CGPoint point = [pan velocityInView:pan.view];
        
        CGPoint contentOffset = self.scrollView.contentOffset;

        //下拉到顶部时,禁止滑动
        if (contentOffset.y <= 0) {
            // velocityInView:得到的速度是带方向的, point.y > 0表示向下滑动
            if (point.y > 0) {
                self.scrollView.scrollEnabled = NO;
                return YES;
            }
        }
    }
    self.scrollView.scrollEnabled = YES;
    return NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        //顶部去除弹簧效果
        scrollView.bounces = (scrollView.contentOffset.y <= 0) ? NO : YES;
    }
}

@end

你可能感兴趣的:(控制UIScrollView滑动方向解决方案)