給模型增加frame數據
- 所有子控件的frame
- cell的高度
@interface XMGStatus : NSObject
/**** 文字\圖片數據 ****/
// .....
/**** frame數據 ****/
/** 頭像的frame */
@property (nonatomic, assign) CGRect iconFrame;
// .....
/** cell的高度 */
@property (nonatomic, assign) CGFloat cellHeight;
@end
- 重寫模型cellHeight屬性的get方法
```objc
- (CGFloat)cellHeight
{
if (_cellHeight == 0) {
// ... 計算所有子控件的frame、cell的高度
}
return _cellHeight;
}
在控制器中
要給tableView設置一個預估的高度,最好是小一點,這樣他才計算了cellheight;
- 實現一個返回cell高度的代理方法
- 在這個方法中返回indexPath位置對應cell的高度
/**
* 返回每一行cell的具體高度
*/
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
Status *status = self.statuses[indexPath.row];
return status.cellH;
}
- 給cell傳遞模型數據
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"status";
// 訪問緩存池
StatusCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 設置數據(傳遞模型數據)
cell.status = self.statuses[indexPath.row];
return cell;
}
新建一個繼承自UITableViewCell
的子類,比如StatusCell
@interface StatusCell : UITableViewCell
@end
在StatusCell.m文件中
- 重寫
-initWithStyle:reuseIdentifier:
方法- 在這個方法中添加所有可能顯示的子控件
- 給子控件做一些初始化設置(設置字體、文字顏色等)
/**
* 在這個方法中添加所有的子控件
*/
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
// ......
}
return self;
}
在StatusCell.h文件中提供一個模型屬性,比如Status模型
@class Status;
@interface XMGStatusCell : UITableViewCell
/** 團購模型數據 */
@property (nonatomic, strong) Status *status;
@end
在XMGStatusCell.m文件中重寫模型屬性的set方法
- 在set方法中給子控件設置模型數據
- (void)setStatus:(Status *)status
{
_status = status;
self.nameLabel.text = status.name;
if (status.isVip) {
self.nameLabel.textColor = [UIColor orangeColor];
self.vipImageView.hidden = NO;
} else {
self.vipImageView.hidden = YES;
self.nameLabel.textColor = [UIColor blackColor];
}
self.text_Label.text = status.text;
if (status.picture) { // 有配圖
self.pictureImageView.hidden = NO;
self.pictureImageView.image = [UIImage imageNamed:status.picture];
} else { // 無配圖
self.pictureImageView.hidden = YES;
}
self.iconImageView.frame = self.status.iconFrame;
self.nameLabel.frame = self.status.nameFrame;
self.vipImageView.frame = self.status.vipFrame;
self.text_Label.frame = self.status.textFrame;
self.pictureImageView.frame = self.status.pictureFrame;
// .......
}