需求:取消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]; 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) { 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
|