控制UIScrollView滑动方向解决方案

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
@interface MyScrollView : UIView <UIGestureRecognizerDelegate>
@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