【问题标题】:Detecting pull-up or dragging of UICollectionView检测 UICollectionView 的上拉或拖动
【发布时间】:2013-10-04 07:48:32
【问题描述】:
我试图想出一种方法,当用户滚动到 UICollectionView 中第一页图像的底部时,自动加载下一页图像。 UITableView(iOS 6)具有用于类似目的(“拉动刷新”)的 refreshControl,可用于刷新或类似的东西。 UICollectionView 是否有类似的选项可用?
有没有办法检测 UICollectionView 是否被拖到最后一行单元格之外,或者它是否正在显示页脚(位于最后一行单元格下方)。然后可以使用此操作触发我的方法来加载下一页图像。
【问题讨论】:
标签:
ios
objective-c
ios6
uicollectionview
【解决方案1】:
由于集合视图继承自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
}
}
希望这会有所帮助!
【解决方案2】:
首先我们需要检测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];
}
}
【解决方案3】:
另一个选项是在请求特定单元格后简单地加载下一个图像或一组图像。例如,如果您只想确保一次预加载 10 张图片...
if (indexPath.row % 10 == 0)
[self preloadImagesStartingAt:indexPath.row + 10 count:10];
如果图像已被请求或存在,则 preload 方法将不执行任何操作,或者发起请求。