[自定義不等高的cell]-純代碼frame方式

給模型增加frame數(shù)據(jù)

  • 所有子控件的frame
  • cell的高度
@interface XMGStatus : NSObject
/**** 文字\圖片數(shù)據(jù) ****/
// .....

/**** frame數(shù)據(jù) ****/
/** 頭像的frame */
@property (nonatomic, assign) CGRect iconFrame;
// .....
/** cell的高度 */
@property (nonatomic, assign) CGFloat cellHeight;
@end
  • 重寫模型cellH屬性的get方法
- (CGFloat)cellHeight
{
    if (_cellHeight == 0) {
        // ... 計(jì)算所有子控件的frame、cell的高度
    }
    return _cellHeight;
}

在控制器中

  • 實(shí)現(xiàn)一個(gè)返回cell高度的代理方法
    • 在這個(gè)方法中返回indexPath位置對應(yīng)cell的高度
/**
 *  返回每一行cell的具體高度
 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XMGStatus *status = self.statuses[indexPath.row];
    return status.cellH;
}
  • 給cell傳遞模型數(shù)據(jù)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"status";
    // 訪問緩存池
    XMGStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

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

    return cell;
}

新建一個(gè)繼承自UITableViewCell的子類,比如XMGStatusCell

@interface XMGStatusCell : UITableViewCell
@end

在XMGStatusCell.m文件中

  • 重寫-initWithStyle:reuseIdentifier:方法
    • 在這個(gè)方法中添加所有可能顯示的子控件
    • 給子控件做一些初始化設(shè)置(設(shè)置字體、文字顏色等)
/**
 *  在這個(gè)方法中添加所有的子控件
 */
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        // ......
    }
    return self;
}

在XMGStatusCell.h文件中提供一個(gè)模型屬性,比如XMGStatus模型

@class XMGStatus;

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

在XMGStatusCell.m文件中重寫模型屬性的set方法

  • 在set方法中給子控件設(shè)置模型數(shù)據(jù)
- (void)setStatus:(XMGStatus *)status
{
    _status = status;

    // .......
}

重寫-layoutSubviews方法

  • 一定要調(diào)用[super layoutSubviews]
  • 在這個(gè)方法中設(shè)置所有子控件的frame
/**
 *  在這個(gè)方法中設(shè)置所有子控件的frame
 */
- (void)layoutSubviews
{
    [super layoutSubviews];

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

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

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