Define scroll direction of UICollectionView, load data from REST

Assuming a standard configuration (up / down), I would like to determine when the user scrolls their UIColletionView up or down (which is a subclass of UIScrollView and corresponds to UIScrollViewDelegate ). I do not see any information directly from the delegate to discover this, although I may have searched for something.

If I know in which direction the user is scrolling, I can use these UICollectionViewDatasource methods to determine if I should load more data from the REST server or clear information that I should already manage a fixed amount of memory.

// If you scroll down, a section appears

 - (UICollectionReusableView *)collectionView:(UICollectionView *)cv viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { 

// If scrolling down, the last cell in the section disappears

 - (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{ 

// If scrolling up, the last cell in the section appears

 - (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath { 

// If you scroll up, the section disappears

 - (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath{ 
+4
source share
2 answers

You can check the UIScrollView (which the UICollectionView inherits) the panGestureRecognizer property and do something like this:

 CGPoint scrollVelocity = [collectionView.panGestureRecognizer velocityInView:collectionView.superview]; if (scrollVelocity.y > 0.0f) { NSLog(@"going down"); } else if (scrollVelocity.y < 0.0f) { NSLog(@"going up"); } 

Swift 3.1 :

 let scrollVelocity = collectionView.panGestureRecognizer.velocityInView(collectionView.superview) if (scrollVelocity.y > 0.0) { print("going down") } else if (scrollVelocity.y < 0.0) { print("going up") } 
+10
source

You can also use this:

 CGPoint translation = [collectionView.panGestureRecognizer translationInView:collectionView.superview]; if (translation.y > 0) { NSLog(@"DOWN"); } else { NSLog(@"UP"); } 

More accurate

0
source

All Articles