一、新建一個繼承自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
