ios UICollectionView detect scroll direction

最后都变了- 提交于 2019-11-29 01:43:01
Douglas Ferreira

Try this:

Add this somewhere in you header:

@property (nonatomic) CGFloat lastContentOffset;

Then override the scrollViewDidScroll: method:

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

Found in Finding the direction of scrolling in a UIScrollView?

this is the best way to get scroll direction, hope this helps you

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

I was trying to find a way to detect if the user is mostly trying to pull vertically or horizontally the scrollView. I give you my solution, I hope it can be useful to anyone :

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

}

This work find for me and I use this to avoid the scrollView to move horizontally when scrolling vertically and opposite.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!