我有一个UIScrollView只允许水平滚动的,我想知道用户滚动的方向(左,右)。我所做的是子类化UIScrollView并覆盖该touchesMoved方法:
UIScrollView
touchesMoved
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesMoved:touches withEvent:event]; UITouch *touch = [touches anyObject]; float now = [touch locationInView:self].x; float before = [touch previousLocationInView:self].x; NSLog(@"%f %f", before, now); if (now > before){ right = NO; NSLog(@"LEFT"); } else{ right = YES; NSLog(@"RIGHT"); } }
但是当我移动时,这个方法有时根本不会被调用。你怎么看?
确定方向相当简单,但请记住,在一个手势过程中,方向可能会发生多次变化。例如,如果您有一个打开分页的滚动视图,并且用户滑动到下一页,则初始方向可能是向右,但如果您打开了反弹,它将暂时没有方向,并且然后短暂地向左走。
要确定方向,您需要使用UIScrollView scrollViewDidScroll委托。在此示例中,我创建了一个名为的变量lastContentOffset,用于将当前内容偏移量与前一个内容偏移量进行比较。如果它更大,则 scrollView 正在向右滚动。如果小于,则 scrollView 向左滚动:
UIScrollView scrollViewDidScroll
lastContentOffset
// somewhere in the private class extension @property (nonatomic, assign) CGFloat lastContentOffset; // somewhere in the class implementation - (void)scrollViewDidScroll:(UIScrollView *)scrollView { ScrollDirection scrollDirection; if (self.lastContentOffset > scrollView.contentOffset.x) { scrollDirection = ScrollDirectionRight; } else if (self.lastContentOffset < scrollView.contentOffset.x) { scrollDirection = ScrollDirectionLeft; } self.lastContentOffset = scrollView.contentOffset.x; // do whatever you need to with scrollDirection here. }
我正在使用以下枚举来定义方向。将第一个值设置为 ScrollDirectionNone 具有在初始化变量时将该方向设置为默认值的额外好处:
typedef NS_ENUM(NSInteger, ScrollDirection) { ScrollDirectionNone, ScrollDirectionRight, ScrollDirectionLeft, ScrollDirectionUp, ScrollDirectionDown, ScrollDirectionCrazy, };