自定义等高的cell(纯代码)

来源:互联网 发布:java学生信息管理系统 编辑:程序博客网 时间:2024/05/19 18:43

自定义等高的cell(纯代码)

标签(空格分隔): ios基础


新建一个继承自UITableViewCell的子类,比如JLTgCell

@interface JLTgCell : UITableViewCell@end

在JLTgCell.m文件中

  • 重写-initWithStyle:reuseIdentifier:方法
    • 在这个方法中添加所有需要显示的子控件
    • 给子控件做一些初始化设置(设置字体、文字颜色等)
/** *  在这个方法中添加所有的子控件 */- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {        // ......    }    return self;}
  • 重写-layoutSubviews方法
    • 一定要调用[super layoutSubviews]
    • 在这个方法中计算和设置所有子控件的frame
/** *  在这个方法中计算所有子控件的frame */- (void)layoutSubviews{    [super layoutSubviews];    // ......}

在JLTgCell.h文件中提供一个模型属性,比如JLTg模型

@class JLTg;@interface JLTgCell : UITableViewCell/** 团购模型数据 */@property (nonatomic, strong) JLTg *tg;@end

在JLTgCell.m中重写模型属性的set方法

  • 在set方法中给子控件设置模型数据
- (void)setTg:(JLTg *)tg{    _tg = tg;    // .......}

在控制器中

  • 注册cell的类型
[self.tableView registerClass:[JLTgCell class] forCellReuseIdentifier:ID];
  • 给cell传递模型数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    // 访问缓存池    JLTgCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];    // 设置数据(传递模型数据)    cell.tg = self.tgs[indexPath.row];    return cell;}
0 0