iOS 纯代码编写“自定义等高tableViewCell”

一、新建一个继承自UITableViewCell的子类,比如BQTgCell
@interface BQTgCell : UITableViewCell
@end
二、在BQTgCell.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];

    // ......
}
三、在BQTgCell.h文件中提供一个模型属性,比如BQTg模型
@class BQTg;

@interface BQTgCell : UITableViewCell
/** 团购模型数据 */
@property (nonatomic, strong) BQTg *tg;
@end
四、在BQTgCell.m中重写模型属性的set方法
  • 在set方法中给子控件设置模型数据
- (void)setTg:(BQTg *)tg
{
    _tg = tg;

    // .......
}
五、在控制器中
  • 注册cell的类型
[self.tableView registerClass:[BQTgCell class] forCellReuseIdentifier:ID];
  • 给cell传递模型数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 访问缓存池
    BQTgCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

    // 设置数据(传递模型数据)
    cell.tg = self.tgs[indexPath.row];

    return cell;
}

效果图:


效果图

实例代码:BQTableViewCell-1
https://github.com/MrLiu-647/BQTableViewCell-1

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容