UITableView中显示的每一个单元都是一个UITableViewCell对象
每个UITableView中,都有三个属性
也就是内部都又3个控件UIImageView 两个UILabel
@property (nonatomic, readonly, retain) UIImageView *imageView ; @property (nonatomic, readonly, retain) UILabel *textLabel ; @property (nonatomic, readonly, retain) UILabel *detailTextLabel ;
通过代码自定义cell 步骤
1. 新建一个继承自UITableView的类
2.1 数据源方法
//然后在数据源方法 -创建自定义的cell - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //1. 创建cell StatusCell *cell = [StatusCell cellWithTableView:tableView]; //2. 经过前两步后肯定又Cell了.给cell设置新的数据. cell.statusFrame = self.statusFrame[indexPath.row]; //3. 返回cell return cell; }
2.2 - 创建Cell内部封装
+ (instancetype)cellWithTableView:(UITableView *)tableview { //0. static修饰局部变量: 可以保证局部变量只分配以此存储空间(只初始化一次) static NSString *ID = @"tag"; //1. 通过一个标识,去缓存池中寻找可循环利用的cell StatusCell *cell = [tableview dequeueReusableCellWithIdentifier:ID]; //2. 如果缓存池找不到, 可循环利用的cell: 创建一个新的cell , 给cell贴个标识 if (cell == nil) { cell = [[StatusCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID]; } return cell; }
3.重写initWithStyle : reusereuseIdentifier: 方法
先在 自定义cell的.m文件中 .initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reusereuseIdentifier{ }方法中添加所有需要显示的子控件 (不需要设置数据和frame)
** 重写方法前首先在自定义cell中创建对应的属性
** 添加所有需要现实的子控件(不需要设置子控件的数据和frame, 子控件要添加到contentView中),并且将创建的控件赋值给属性
** 进行子控件一次性的属性设置(有些属性只需要设置一次,比如字体/固定图片等)
@interface MessageCell() // 时间 @property (nonatomic, weak)UILabel *timeView; // 头像 @property (nonatomic, weak)UIImageView *iconView; // 正文 @property (nonatomic, weak)UIButton *textView; @end @implementation MessageCell - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) { //添加所有子控件 //时间 UILabel *timeView = [[UILabel alloc] init]; [self.contentView addSubview:timeView]; self.timeView = timeView; //头像 UIImageView *iconView = [[UIImageView alloc] init]; [self.contentView addSubview:iconView]; self.iconView = iconView; //正文 UIButton *textView = [[UIButton alloc] init]; [self.contentView addSubview:textView]; self.textView = textView; } return self; } @end
4. 提供两个模型
** 数据模型 : 存放cell显示的文字数据 , 图片数据 , 等等
** frame模型 : 存放数据模型 / 所有子控件的frame / cell的高度 / 等等
5.自定义cell拥有一个frame模型(不要数据模型);
6. 重写模型属性的setter方法, 在这个方法中设置子控件的显示数据和frame
然后在自定义cell中添加一个模型属性,并且在该属性的 set方法中设置子控件的显示数据和frame(控制器传入模型并赋值该模型属性后,在set方法中执行 设置子控件数据,和设置frame的方法)
7. frame模型数据的初始化采取预加载的放似乎(每一个cell对应的frame模型数据只加载一起)