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

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

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

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

在控制器中

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

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

    return cell;
}

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

@interface XMGStatusCell : UITableViewCell
@end

在XMGStatusCell.m文件中

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

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

@class XMGStatus;

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

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

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

    // .......
}

重寫-layoutSubviews方法

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

    // ......
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容