UICollectionView pull up or drag detection

I am trying to find a way to automatically load the next page of images when the user scrolls to the bottom of the first page of images in the UICollectionView. UITableView (iOS 6) has a refreshControl for a similar purpose ("Pull to refresh"), which can be used to update or something similar. Is there a similar option for UICollectionView?

Is there a way to detect that a UICollectionView is being dragged outside the last row of cells, or if it displays a footer (which is below the last row of cells). You can then use this action to launch my method to load the next page of images.

+6
source share
3 answers

Since collection views inherit from UIScrollView , you can implement scroll delegate methods to detect scroll motion. For example, you can implement scrollViewDidScroll and use the contentOffset property to measure how far the user scrolls.

 - (void)scrollViewDidScroll:(UIScrollView *)scrollView { CGFloat offsetY = scrollView.contentOffset.y; CGFloat contentHeight = scrollView.contentSize.height; if (offsetY > contentHeight - scrollView.frame.size.height) { //start loading new images } } 

Hope this helps!

+21
source

First, we need to determine if the collection view has passed a certain percentage of scrolling and, if it is, start loading the next page. See below:

 // Outside the implementation block: static const CGFloat kNewPageLoadScrollPercentageThreshold = 0.66; static BOOL ShouldLoadNextPage(UICollectionView *collectionView) { CGFloat yOffset = collectionView.contentOffset.y; CGFloat height = collectionView.contentSize.height - CGRectGetHeight(collectionView.frame); return yOffset / height > kNewPageLoadScrollPercentageThreshold; } // Inside the implementation block: #pragma mark - UICollectionViewDelegate - (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath { BOOL shouldLoadNextPage = ShouldLoadNextPage(collectionView); if (shouldLoadNextPage && !_pageLoading) { [self _loadNextPage]; } } 
+4
source

Another option is to simply load the next image or set of images after requesting a specific cell. For example, if you just want to make sure that you preload 10 images at a time ...

 if (indexPath.row % 10 == 0) [self preloadImagesStartingAt:indexPath.row + 10 count:10]; 

The preload method will then do nothing if images are requested or exist or initiate a request.

+1
source

Source: https://habr.com/ru/post/954814/


All Articles