为了账号安全,请及时绑定邮箱和手机立即绑定

在UIScrollView中查找滚动方向?

在UIScrollView中查找滚动方向?

梵蒂冈之花 2019-07-31 15:41:30
在UIScrollView中查找滚动方向?我UIScrollView只允许水平滚动,我想知道用户滚动的方向(左,右)。我做的是继承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");     }}但是当我移动时,这种方法有时根本不会被调用。你怎么看?
查看完整描述

3 回答

?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

确定方向相当简单,但请记住,方向可以在手势过程中多次改变。例如,如果您有一个打开分页的滚动视图,并且用户滑动以转到下一页,则初始方向可能是向右的,但如果您打开了弹跳,它将暂时完全没有方向然后简单地向左走。

要确定方向,您需要使用UIScrollView scrollViewDidScroll委托。在这个示例中,我创建了一个名为变量的变量lastContentOffset,用于将当前内容偏移量与前一个内容偏移量进行比较。如果它更大,则scrollView向右滚动。如果它小于那么scrollView向左滚动:

// 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,};


查看完整回答
反对 回复 2019-07-31
?
缥缈止盈

TA贡献2041条经验 获得超4个赞

...我想知道用户滚动的方向(左,右)。

在这种情况下,在iOS 5及更高版本上,使用它UIScrollViewDelegate来确定用户平移手势的方向:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ 
    if ([scrollView.panGestureRecognizer translationInView:scrollView.superview].x > 0) {
        // handle dragging to the right
    } else {
        // handle dragging to the left
    }}


查看完整回答
反对 回复 2019-07-31
?
暮色呼如

TA贡献1853条经验 获得超9个赞

使用scrollViewDidScroll:是查找当前方向的好方法。

如果您想在用户完成滚动知道方向,请使用以下命令:

@property (nonatomic) CGFloat lastContentOffset;- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.lastContentOffset = scrollView.contentOffset.x;}- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (self.lastContentOffset < scrollView.contentOffset.x) {
        // moved right
    } else if (self.lastContentOffset > scrollView.contentOffset.x) {
        // moved left
    } else {
        // didn't move
    }}


查看完整回答
反对 回复 2019-07-31
  • 3 回答
  • 0 关注
  • 715 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信