与UITableViewCell不同的是,通过 xib 或 storyboard创建的 UICollectionViewCell在xib中不显示contentView,无法直接向contentView中添加子视图。
最终选择向contentView中添加子视图的方法是initWithFrame:(CGRect)frame方法中代码添加:
.h代码
@interfacePhotoEditOptionCell :UICollectionViewCell
@property(nonatomic,retain)UIImageView * iconView;
@property(nonatomic,assign)BOOL isEnable;
@end
.m代码
@implementationPhotoEditOptionCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
-(instancetype)initWithFrame:(CGRect)frame{
if(self= [superinitWithFrame:frame]) {
self.iconView = [[UIImageView alloc]init];
[self.contentView addSubview:self.iconView];
WEAKSELF
[self.iconView mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(weakSelf.contentView);
}];
}
return self;
}
@end
参考:https://stackoverflow.com/questions/34647150/add-sub-views-into-uicollectionviewcells-contentview-via-xib-or-storyboard/34676046