计算cell的高度

来源:互联网 发布:淘宝怎么买微信号 编辑:程序博客网 时间:2024/05/05 14:45

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号

0 0
原创粉丝点击