网上大部分的boundingRectWithSize和sizeWithFont 计算出来的宽高在某些有特殊情况下(如链接中有\n等等)计算出来的还是有偏差不准,此时用NSAttributedString和label的attributedText计算会迎刃而解
1.给model的.h文件添加一个NSAttributedString属性
/** 带有属性的(特殊文字会高亮显示\显示表情) */
@property (nonatomic, copy) NSAttributedString *attributedText;
2..m重写text的set方法
//重写set
- (void)setMessageStr:(NSString *)messageStr
{
_messageStr = messageStr;
//计算出attributedText
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:messageStr];
[attrString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, messageStr.length)];
_attributedText = attrString;
}
3.cell.m文件
//用attributedText解决有时高度计算不准的bug
self.contentL.attributedText = privateLetterMyModel.attributedText;
//最终计算出来的准确的size
CGSize frame = [self.contentL.attributedText boundingRectWithSize:CGSizeMake(ScreenWidth - 120, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
4.viewController中计算cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
TestModel *model = self.dataArr[indexPath.row];
CGSize frame = [CalculateSize sizeForNoticeTitle:model.messageStr font:[UIFont systemFontOfSize:16] maxW: ScreenWidth - 120];
CGSize frame = [model.attributedText boundingRectWithSize:CGSizeMake(ScreenWidth - 120, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
return frame.height ;
}
5.从服务器用mdel.text获取数据(以为重写了setText方法所以会自动获取attributedText)
附加以前我的不完善的另一篇文章链接:http://blog.csdn.net/wqs1028/article/details/51205785