默认情况下,除了改变背景色,UICollectionViewCell不允许我们进行太多的配置。我们需要创建UICollectionViewCell的子类来实现对cell的配置。
1.纯代码实现:
创建一个Cocoa Touch Class
类,命名为SScollectionViewCell
,该类继承自UICollectionViewCell
类,代码实现如下:
#import <UIKit/UIKit.h>
@interface SScollectionViewCell : UICollectionViewCell
@property(nonatomic,strong)UIImageView* imgView;
@property(nonatomic,strong)UILabel* show;
@end
#import "SScollectionViewCell.h"
@implementation SScollectionViewCell
-(instancetype)initWithFrame:(CGRect)frame{
self=[super initWithFrame:frame];
//self相当于一个容器,可以在里面添加任意控件来定制自己的cell。
if (self) {
self.backgroundColor=[UIColor grayColor];
//add UIImageView
self.imgView=[[UIImageView alloc] initWithFrame:CGRectMake(5, 5, CGRectGetWidth(self.frame)-10, CGRectGetHeight(self.frame)-30)];
self.imgView.backgroundColor=[UIColor groupTableViewBackgroundColor];
[self addSubview:self.imgView];
//add UILabel
self.show=[[UILabel alloc] initWithFrame:CGRectMake(5, CGRectGetMaxY(self.imgView.frame), CGRectGetWidth(self.frame)-10, 20)];
self.show.backgroundColor=[UIColor greenColor];
self.show.textAlignment=NSTextAlignmentCenter;
[self addSubview:self.show];
}
return self;
}
@end
二.利用Xib
实现:
创建一个创建一个Cocoa Touch Class
类,命名为SScollectionViewCell
,该类继承自UICollectionViewCell
类,并且创建一个Xib
文件,将创建好的类与Xib
文件相关联,我们可以在Xib
文件中任意定制我们的cell外观,注意要将Xib
文件添加的控件利用IBOutlet
将其管理起来。
使用创建好的自定义UICollectionViewCell
类时,要为cell
注册nib
文件,否则的话无法显示:
UINib *nib = [UINib nibWithNibName:@"SScell"
bundle: [NSBundle mainBundle]];
[self.collectionView registerNib:nib forCellWithReuseIdentifier:ID];