iOS 开发 列表预加载

豆瓣-预加载.gif

最近增加了一个小需求,就是部分页面上拉加载的时候添加“预加载”功能,类似于上图中豆瓣的这样,其实这个逻辑很简单,就是在快要滑动到列表底部的时候去调用上拉加载的方法。

这里简单介绍两种实用方法:

一、willDisplayCell

- (void)collectionView:(UICollectionView *)collectionView 
       willDisplayCell:(UICollectionViewCell *)cell 
    forItemAtIndexPath:(NSIndexPath *)indexPath {
    // 列表中是否存在更多数据
    if (self.dataSource.hasMoreData == NO) {
        return;
    }
    
    if (indexPath.row > [self.dataSource numberOfDatasInSection:indexPath.section] * 0.8) {
        [self.dataSource loadMoreDataWithCompletion:nil];
    }
}

二、scrollViewDidScroll

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 列表中是否存在更多数据
    if (self.dataSource.hasMoreData == NO) {
        return;
    }

    CGFloat threshold = 0.8;
    CGFloat current = scrollView.contentOffset.y + scrollView.frame.size.height;
    CGFloat total = scrollView.contentSize.height;
    CGFloat ratio = current / total;
    
    if (ratio >= threshold) {
        [self.dataSource loadMoreDataWithCompletion:nil];
    }
}

三、注意:

注意,这样写会产生问题,就是当列表滑动0.8的时候触发网络加载,在未完成网络加载的情况下,列表滑动0.81回再次触发网络加载,我是在loadMoreDataWithCompletion里面有网络加载判断,所以,直接copy代码的老铁们需要注意一下,有好的方法也可以留言,大家一起改进

- (void)loadMoreDataWithCompletion:(void (^)(BOOL))completion {
    // 当前网络正在加载
    if (super.statusObject.isLoading) {
        return;
    }
    ......
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容