#UITableViewCell#自定義不等高的cell-純代碼(frame)

新建一個繼承自UITableViewCell的子類,比如XMGTgCell

@interface XMGTgCell : UITableViewCell
@end

在XMGTgCell.m文件中

  • 重寫-initWithStyle:reuseIdentifier:方法
    • 在這個方法中添加所有需要顯示的子控件
    • 給子控件做一些初始化設(shè)置(設(shè)置字體、文字顏色等)
/**
 *  在這個方法中添加所有的子控件
 */
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        // ......
    }
    return self;
}
  • 重寫-layoutSubviews方法
    • 一定要調(diào)用[super layoutSubviews]
    • 在這個方法中計算和設(shè)置所有子控件的frame
/**
 *  在這個方法中計算所有子控件的frame
 */
- (void)layoutSubviews
{
    [super layoutSubviews];

    // ......
}

在XMGTgCell.h文件中提供一個模型屬性,比如XMGTg模型

@class XMGTg;

@interface XMGTgCell : UITableViewCell
/** 團(tuán)購模型數(shù)據(jù) */
@property (nonatomic, strong) XMGTg *tg;
@end

在XMGTgCell.m中重寫模型屬性的set方法

  • 在set方法中給子控件設(shè)置模型數(shù)據(jù)
- (void)setTg:(XMGTg *)tg
{
    _tg = tg;

    // .......
}

在控制器中

  • 注冊cell的類型
[self.tableView registerClass:[XMGTgCell class] forCellReuseIdentifier:ID];
  • 給cell傳遞模型數(shù)據(jù)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 訪問緩存池
    XMGTgCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

    // 設(shè)置數(shù)據(jù)(傳遞模型數(shù)據(jù))
    cell.tg = self.tgs[indexPath.row];

    return cell;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容