如何从UICollectionView中检测滚动方向?

17

我有一个UICollectionView,想要检测滚动方向。我有两种不同的滚动动画样式,分别用于向下和向上滚动。所以我必须学会滚动方向。

CGPoint scrollVelocity = [self.collectionView.panGestureRecognizer
velocityInView:self.collectionView.superview];

if (scrollVelocity.y > 0.0f)   
NSLog(@"scroll up");

else if(scrollVelocity.y < 0.0f)    
NSLog(@"scroll down");

这只是手指触摸的工作。对我无效。

4个回答

31

试试这个:

在你的头部某处添加如下内容:

@property (nonatomic) CGFloat lastContentOffset;

然后重写 scrollViewDidScroll: 方法:

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.lastContentOffset > scrollView.contentOffset.y)
    {
        NSLog(@"Scrolling Up");
    }
    else if (self.lastContentOffset < scrollView.contentOffset.y)
    {
        NSLog(@"Scrolling Down");
    }

    self.lastContentOffset = scrollView.contentOffset.y;
}

发现于在UIScrollView中找到滚动方向的方法?


5

这是获取滚动方向的最佳方式,希望能对您有所帮助。

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {

    CGPoint targetPoint = *targetContentOffset;
    CGPoint currentPoint = scrollView.contentOffset;

    if (targetPoint.y > currentPoint.y) {
        NSLog(@"up");
    }
    else {
        NSLog(@"down");
    }
}

拖动...不就是使用手指拖动吗?即使没有用户的手指,滚动也可能发生,是吧? - iWheelBuy

5

Swift 4.2

private var lastContentOffset: CGFloat = 0
func scrollViewDidScroll(_ scrollView: UIScrollView) {

    if lastContentOffset > scrollView.contentOffset.y && lastContentOffset < scrollView.contentSize.height - scrollView.frame.height {
        // move up
        print("move up")
        originalHeight ()
    } else if lastContentOffset < scrollView.contentOffset.y && scrollView.contentOffset.y > 0 {
        // move down
        print("move down")
        minimizeHeaderView()
    }

    // update the new position acquired
    lastContentOffset = scrollView.contentOffset.y
}

2
我正在寻找一种检测用户在 scrollView 中主要是水平拉动还是垂直拉动的方法。现在我分享我的解决方案,希望对大家有用:
CGPoint _lastContentOffset;

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    _lastContentOffset = scrollView.contentOffset;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    if (ABS(_lastContentOffset.x - scrollView.contentOffset.x) < ABS(_lastContentOffset.y - scrollView.contentOffset.y)) {
        NSLog(@"Scrolled Vertically");
    } else {
        NSLog(@"Scrolled Horizontally");
    }

}

这项工作对我很有帮助,我使用它来避免在垂直滚动和水平滚动时scrollView的水平移动。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接