iOS10中,UICollectionView和UITableView增加了一個協(xié)議屬性prefetchDataSource。與dataSource屬性相似,將對象賦值給列表的prefetchDataSource屬性,并遵循相應(yīng)協(xié)議,即UICollectionViewDataSourcePrefetching,即可在該對象中實現(xiàn)協(xié)議中的兩方法,從而達(dá)到列表內(nèi)容預(yù)加載的效果。值得注意的是,iOS10中列表的prefetchingEnabled默認(rèn)為YES,如果用自己的辦法優(yōu)化(比如每個cell內(nèi)容都使用異步加載的方式),那需要將此屬性設(shè)置為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
collectionView.delegate? ? ? ? ? ? ? ? ? ? ? = self;
collectionView.dataSource? ? ? ? ? ? ? ? ? ? = self;
collectionView.prefetchDataSource? ? ? ? ? ? = self;
}
當(dāng)滑動列表速度超過cellForItemAtIndexPaths承受數(shù)據(jù)加載能力時候,會調(diào)用該方法。因此,列表初始化時、滑的很慢時都不會調(diào)用,其中indexPaths參數(shù)為即將準(zhǔn)備進(jìn)入可視區(qū)域的cell對應(yīng)的indexPath數(shù)組。
- (void)tableView:(UITableView *)tableViewprefetchRowsAtIndexPaths:(NSArray*)indexPaths { ? ?
for (NSIndexPath *indexPath in indexPaths) {
//請求或處理圖片
? ? }
}
從一定角度來看,collection view 的預(yù)加載請求只是試圖優(yōu)化未來不確定狀態(tài)的一種猜測,這種狀態(tài)可能并不會真實發(fā)生。例如,如果滾動速度放緩或者完全反轉(zhuǎn)方向,那些已經(jīng)請求過的預(yù)加載 cell 可能永遠(yuǎn)都不會確切地顯示。
- (void)tableView:(UITableView *)tableViewcancelPrefetchingForRowsAtIndexPaths:(NSArray *)indexPaths;
整理轉(zhuǎn)載:
https://juejin.im/entry/580f21d9da2f60004f42a9f8
https://www.sitepoint.com/uicollectionview-datasourceprefetching-example-and-explanation/