How can I detect the scroll direction from the UICollectionView?

sonifex picture sonifex · Jun 29, 2014 · Viewed 24.5k times · Source

I have a UICollectionView. I want to detect scroll direction. I have a two different animation style for scroll down and scroll up. So I must learn scroll direction.

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

This is just work at finger touched. Not work for me

Answer

Douglas Ferreira picture Douglas Ferreira · Jun 30, 2014

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?