ios UICollectionView检测滚动方向

时间:2014-06-29 21:27:09

标签: ios objective-c uicollectionview uigesturerecognizer uipangesturerecognizer

我有一个collectionView。我想检测滚动方向。我有两种不同的动画风格,可以向下滚动并向上滚动。所以我必须学习滚动方向。

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 个答案:

答案 0 :(得分:28)

试试这个:

在标题中的某处添加:

@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;
}

Finding the direction of scrolling in a UIScrollView?

中找到

答案 1 :(得分:4)

这是获得滚动方向的最佳方式,希望这有助于你

- (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");
    }
}

答案 2 :(得分: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在垂直和相反的方向滚动时水平移动。

答案 3 :(得分:0)

Swift 4.2

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

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

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