在iOS10中,苹果为UICollectionViewCell引入了Pre-Fetching预加载机制用于提升它的性能。主要引入了一个新的数据源协议UICollectionViewDataSourcePrefetching,包含两个方法:
@protocol UICollectionViewDataSourcePrefetching <NSObject>
@required
// 预加载数据
- (void)collectionView:(UICollectionView *)collectionView prefetchItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths NS_AVAILABLE_IOS(10_0);
@optional
// 取消提前加载数据
- (void)collectionView:(UICollectionView *)collectionView cancelPrefetchingForItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths NS_AVAILABLE_IOS(10_0);
@end
网上搜了一大圈,讲述原理的(翻译文档)的文章很多,有干货的Demo很少,于是乎自己摸索了一下,写了一个简单的案例,在此记录并分享一下。
运行环境:Xcode 8.2.1 + iOS 10.2
核心步骤:
1、遵从 UICollectionViewDataSourcePrefetching 协议
2、实现 collectionView:prefetchItemsAtIndexPaths 方法和collectionView:cancelPrefetchItemsAtIndexPaths 方法(可选)
3、将第1步中遵从协议的类设置为 UICollectionView 的 prefetchDataSource 属性
实现
一、创建UICollectionViewFlowLayout
自己写一个类继承自UICollectionViewFlowLayout
@implementation MyCollectionViewFlowLayout
-(void)prepareLayout{
self.minimumLineSpacing = 1;//垂直间距
self.minimumInteritemSpacing = 0;//水平间距
self.sectionInset = UIEdgeInsetsMake(0, 0, 8, 0);//分组间距
}
@end
二、用XIB定义一个
里面就一个UIImageView,然后拽线设置一个IBOutlet