iOS 开发 UICollectionView使用Xib自定义cell

平时直接在Storyboard中拖拽UICollectionView,然后画Cell。但是项目多个View都用到该Cell,于是将其提出来复用。

1、创建一个继承自UICollectionViewCell的类,暂且命名为ResourceCollectionViewCell,勾选Also create XIB file 来创建xib文件(当然,你也可以单独创建),这样就创建了三个文件


2、删除Xib中默认的View,拖一个Collection View Cell控件进去,然后在里面添加相应控件和约束。

3、设置Xib中CollectionViewCell的Class为“ResourceCollectionViewCell”,然后指定Identifier为“ResourceCollectionViewCell”(Identifier是为了Cell复用,可以自定义)
 

 

4、准备工作就绪,下面就开始使用了。使用前CollectionView需要先注册自定义的Cell,注册也有两个方法:

方法一:使用registerNib方法

[self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([ResourceCollectionViewCell class]):[NSBundle mainBundle]] forCellWithReuseIdentifier:@"ResourceCollectionViewCell"];
方法二:使用registerClass方法

[self.collectionView registerClass:[ResourceCollectionViewCell class] forCellWithReuseIdentifier:@"ResourceCollectionViewCell"];
但是需要重写ResourceCollectionViewCell的initWithFrame:方法,否则显示不了Cell的内容

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self = [[NSBundle mainBundle]loadNibNamed:@"ResourceCollectionViewCell" owner:self options:nil].lastObject;
    }
    return self;
}
5、在UICollectionViewDataSource代理方法

(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 中返回cell。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID=@"ResourceCollectionViewCell";
    ResourceCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    Resource *data=self.data.recommendation[indexPath.row];
    cell.data=data;
    return cell;
}

6、效果
--------------------- 


作者:cuisea 
来源:CSDN 
原文:https://blog.csdn.net/cuihaiyang/article/details/55057199 
版权声明:本文为博主原创文章,转载请附上博文链接!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值