1、- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
返回cell的高度。
因为这个方法会随着tableView的上下拖动,频繁调用,所以我们把计算cell的高度代码放到模型里。
2、cell的模型Topic.h提供一个额外的属性
/****** 额外的辅助属性 *****/
/**
* cell的高度
*/
@property(nonatomic,assign,readonly)CGFloat cellHeight;
Topic.m里实现:
#import "Topic.h"
@implementation Topic
{
CGFloat _cellHeight;
}
- (CGFloat)cellHeight
{
if (!_cellHeight) {
// 文字内容的最大尺寸
CGSize maxSize = CGSizeMake([UIScreen mainScreen].bounds.size.width - 4 * TopicCellMargin, MAXFLOAT);
// 计算文字的高度
CGFloat textH = [self.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size.height;
// cell的高度
_cellHeight = TopicCellTextY + textH + TopicCellBottomBarH + 2 * TopicCellMargin;
}
return _cellHeight;
}
@end
其他:cellHeight属性我们设置为readonly防止外面被修改,所以同时需要增加局部变量
{
CGFloat _cellHeight;
}
另外注意我们在xib上label的文字大小要和这里一致 14号