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 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/ljc_563812704/article/details/98491902