8

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

Is there a way to detect that a UICollectionView is being dragged beyond the last line of cells, or if it is displaying the footer (which is below the last line of cells). This action can then be used to trigger my method to load the next page of images.

4

3 回答 3

23

由于集合视图继承自UIScrollView,因此您可以实现滚动视图委托方法来检测滚动运动。例如,您可以实现scrollViewDidScroll并使用该contentOffset属性来衡量用户向下滚动的距离。

- (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
    }
}

希望这可以帮助!

于 2013-09-27T23:21:13.527 回答
4

首先我们需要检测collection view是否已经超过了一定的滚动百分比,如果有,就开始加载下一页。见下文:

//  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];
  }
}
于 2015-01-06T03:55:41.950 回答
1

另一种选择是在请求特定单元格后简单地加载下一个图像或一组图像。例如,如果您只想确保一次预加载 10 个图像...

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

如果图像已被请求或存在,或者启动请求,则 preload 方法将不执行任何操作。

于 2013-09-27T23:31:24.707 回答