UICollectionView prefetch

iOS10中,UICollectionView和UITableView增加了一个协议属性prefetchDataSource。与dataSource属性相似,将对象赋值给列表的prefetchDataSource属性,并遵循相应协议,即UICollectionViewDataSourcePrefetching,即可在该对象中实现协议中的两方法,从而达到列表内容预加载的效果。值得注意的是,iOS10中列表的prefetchingEnabled默认为YES,如果用自己的办法优化(比如每个cell内容都使用异步加载的方式),那需要将此属性设置为NO:

if ([_inputSelectView respondsToSelector:@selector(setPrefetchingEnabled:)])
{
    _inputSelectView.prefetchingEnabled  = NO;
}

举个例子:

@interface NLViewController <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDataSourcePrefetching>

@end

static NSString *cellIdentifier = @"cell";

@implementation NLViewController

#pragma mark - View lifeCycle

- (void)viewDidLoad {
[super viewDidLoad];

collectionView.delegate                      = self;
collectionView.dataSource                    = self;
collectionView.prefetchDataSource            = self;
}

当滑动列表速度超过cellForItemAtIndexPaths承受数据加载能力时候,会调用该方法。因此,列表初始化时、滑的很慢时都不会调用,其中indexPaths参数为即将准备进入可视区域的cell对应的indexPath数组。

- (void)tableView:(UITableView *)tableViewprefetchRowsAtIndexPaths:(NSArray*)indexPaths {    

for (NSIndexPath *indexPath in indexPaths) {

//请求或处理图片

    }

}

从一定角度来看,collection view 的预加载请求只是试图优化未来不确定状态的一种猜测,这种状态可能并不会真实发生。例如,如果滚动速度放缓或者完全反转方向,那些已经请求过的预加载 cell 可能永远都不会确切地显示。

- (void)tableView:(UITableView *)tableViewcancelPrefetchingForRowsAtIndexPaths:(NSArray *)indexPaths;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.