UICollectionView学习<2>之UICollectionViewCell的自定义

默认情况下,除了改变背景色,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];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值