UICollectionViewController相关注意事项

相似点:
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];

}
  1. 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可省略空值判断的步骤。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值