cell樣式如下

cell樣式.png
1.cell
@interface QPStatusCell ()
/** 圖像 */
@property (nonatomic, weak)IBOutlet UIImageView *iconImageView;
/** 昵稱 */
@property (nonatomic, weak)IBOutlet UILabel *nameLabel;
/** vip */
@property (nonatomic, weak)IBOutlet UIImageView *vipImageView;
/** 正文 */
@property (nonatomic, weak)IBOutlet UILabel *text_Label;
/** 配圖 */
@property (nonatomic, weak)IBOutlet UIImageView *pictureImageView;
@end
@implementation QPStatusCell
- (void)awakeFromNib
{
// 手動(dòng)設(shè)置文字的最大寬度(讓label能夠計(jì)算出自己最真實(shí)的尺寸)
self.text_Label.preferredMaxLayoutWidth = [UIScreen mainScreen].bounds.size.width - 20;
}
/**
* 設(shè)置子控件的數(shù)據(jù)
*/
- (void)setStatus:(XMGStatus *)status
{
_status = status;
self.iconImageView.image = [UIImage imageNamed:status.icon];
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;
}
}
- (CGFloat)cellHeight
{
// 強(qiáng)制刷新(label根據(jù)約束自動(dòng)計(jì)算它的寬度和高度)
[self layoutIfNeeded];
CGFloat cellHeight = 0;
if (self.status.picture) { // 有配圖
cellHeight = CGRectGetMaxY(self.pictureImageView.frame) + 10;
} else { // 無配圖
cellHeight = CGRectGetMaxY(self.text_Label.frame) + 10;
}
return cellHeight;
}
@end
2.UITableViewController
@interface ViewController ()
/** 所有的微博數(shù)據(jù) */
@property (nonatomic, strong) NSArray *statuses;
@end
@implementation ViewController
- (NSArray *)statuses
{
if (!_statuses) {
_statuses = [QPStatus mj_objectArrayWithFilename:@"statuses.plist"];
}
return _statuses;
}
- (void)viewDidLoad {
[super viewDidLoad];
// 設(shè)置估算高度 (減少tableView:heightForRowAtIndexPath:的調(diào)用次數(shù))
self.tableView.estimatedRowHeight = 200;
}
NSString *ID = @"status";
#pragma mark - 數(shù)據(jù)源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.statuses.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 訪問緩存池
QPStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 傳遞模型數(shù)據(jù)
cell.status = self.statuses[indexPath.row];
return cell;
}
QPStatusCell *cell;
#pragma mark - 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 創(chuàng)建一個(gè)臨時(shí)的cell(目的:傳遞indexPath對(duì)應(yīng)這行的模型,布局內(nèi)部所有的子控件,得到cell的高度)
if (cell == nil) {
cell = [tableView dequeueReusableCellWithIdentifier:ID];
}
// 傳遞模型數(shù)據(jù)
cell.status = self.statuses[indexPath.row];
return cell.cellHeight;
}
@end