免费开源的iOS开发学习平台

UICollectionView详解:9-自定义Cell

与UITableViewCell不同,UICollectionViewCell中默认情况下没有附带任何控件,因此,如果在开发中使用到集合视图,其单元格100%都需要定制。

自定义单元格Cell

在使用集合视图时,当我们需要使用自定义的单元格,可以采用如下的3个核心步骤进行实现。

  1. 创建自定义单元格类,继承自UICollectionViewCell类,并对该单元格的样式进行定制(使用代码编写,或使用Xib);
  2. 在创建该类的单元格对象之前,提前注册,可以在viewDidLoad方法中,或者在创建集合视图对象后立即注册单元格;
  3. 通过UICollectionViewDataSource中的方法,创建单元格对象,并为其提供需要展示的数据。

示例代码

下方的示例代码,创建了一个自定义单元格类,并在后续的代码中实现了对自定义单元格对象的创建以及展示。

  • 新建自定义UICollectionViewCell类,继承自UICollectionViewCell类。这里我们同时创建一个Xib文件用于单元格样式的定制

  • 根据项目开发的需要,设计单元格的样式,例如,我们添加了一个UIImageView控件以及一个UILabel控件,控件添加完毕后,我们使用自动布局技术,对控件的位置与大小设置约束关系;

  • 连线,把自定义单元格Cell中的控件,连线到MYCollectionViewCell.h文件中。
#import <UIKit/UIKit.h>
@interface MYCollectionViewCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIImageView *photoImageView;
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
  • 创建集合视图,并注册单元格cell
@interface ViewController ()<UICollectionViewDataSource>
@property (nonatomic,strong) UICollectionView *collectionView;
@end
- (UICollectionView *)collectionView {
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];

        _collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        //取出cell的xib
        UINib *nib = [UINib nibWithNibName:@"MYCollectionViewCell" bundle:nil];
        MYCollectionViewCell *cell = [nib instantiateWithOwner:nil options:nil].lastObject;
        // 根据xib中cell, 设置itemsize的大小
        flowLayout.itemSize = cell.frame.size;
        [_collectionView registerNib:nib forCellWithReuseIdentifier:@"MYCollectionViewCell"];
    }
    return _collectionView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.collectionView];
}
  • 设置单元格Cell的数据源。在cellForItemAtIndexPath:数据源方法中,创建单元格对象并为单元格中的控件提供数据。
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MYCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MYCollectionViewCell" forIndexPath:indexPath];
    cell.photoImageView.image = [UIImage imageNamed:@"99logo"];
    cell.label.text = @"九九学院";
    cell.backgroundColor = [UIColor yellowColor];
    return cell;
}

运行效果:

示例代码

https://github.com/99ios/8.3.9