简书首页

iOS 开发 列表预加载

2018-10-20  本文已影响170人  强子ly
豆瓣-预加载.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;
    }
    ......
}
上一篇 下一篇

猜你喜欢

热点阅读