相似点:
1.UICollectionViewController和UITableViewController很相似, 同样拥有“数据源方法”和“代理方法”
2.同样有可重用cell的思想,来优化性能
注意点:
1.UICollectionViewController的cell不像UITableViewController那样在初始化时可以选择默认模式,通常需要自定义布局,调整设置。
因此需要重写init方法,当初始化一个UICollectionViewController时调用系统flowLayout布局
#pragma mark - 重写init方法:
-(instancetype)init
{
// 流布局
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
// 设置布局
flowLayout.minimumLineSpacing = 10;
flowLayout.minimumInteritemSpacing = 0;
flowLayout.itemSize = CGSizeMake(95, 95);
flowLayout.sectionInset = UIEdgeInsetsMake(20, 0, 0, 0);
return [super initWithCollectionViewLayout:flowLayout];
}
- UICollectionViewController数据源方法:
// 分组个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
// 每组内有多少个item
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return self.products.count;
}
其中,注意UICollectionViewController可重用cell的方法,后面只可选“forIndexPath:indexPath];”,表明,如果缓存池中没有可重用的cell,那么将从storyboard中加载。
容易报错!!!
//每个item的明细
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
ProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
// 得到cell的数据模型
ProductModel *pModel = self.products[indexPath.item];
// 设置数据
cell.proModel = pModel;
return cell;
}
3.鉴于上面一点,对于自定义创建的cell(如XIB创建),我们要事先注册
static NSString * const reuseIdentifier = @"Cell";
- (void)viewDidLoad {
[super viewDidLoad];
// 从Xib注册cell
UINib *Nib = [UINib nibWithNibName:@"ProductCell" bundle:nil];
[self.collectionView registerNib:Nib forCellWithReuseIdentifier:reuseIdentifier];
}
4.总结:
1.自定义cell时,
1) 若使用nib,使用 registerNib: 注册,dequeue时会调用 cell 的 -(void)awakeFromNib
2) 不使用nib,使用 registerClass: 注册, dequeue时会调用 cell 的 - (id)initWithStyle:withReuseableCellIdentifier:
2.需不需要注册?
1) 使用dequeueReuseableCellWithIdentifier:可不注册,但是必须对获取回来的cell进行判断是否为空,若空则手动创建新的cell;
2) 使用dequeueReuseableCellWithIdentifier:forIndexPath:必须注册,但返回的cell可省略空值判断的步骤。