最近在项目开发中,好奇把Xcode升级到了8.0,结果造成了自定义TableViewCell中的TTTAttributedLabel的高度计算出了问题,会出现字体只显示一半的情况(备注:项目采用的是自定义字体苹方常规)。为了解决了这个问题,我尝试了以下方法:
1、在计算完高度返回时,再加上一定的数值,比如 return cellheight+30;
这样看来好像字体是可以完全显示了,可是行数多了,还是会显示不全。于是否决了。
2、计算时改变字体大小,这样可以完美解决问题,比起第一种方法更安全啊。
于是就有了以下代码:
if(!_contenttxt){
_contenttxt=[[TTTAttributedLabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
_contenttxt.textColor=[UIColor blackColor];
//设置自动行数与字符换行
[_contenttxt setNumberOfLines:0];
_contenttxt.lineBreakMode = NSLineBreakByWordWrapping;
_contenttxt.font =[UIFont fontWithName:@"PingFangSC-Regular" size:13];
_contenttxt.lineSpacing=6;
[self.contentView addSubview:_contenttxt];
}
重点是下面的计算cell的height:
注意,第一行代码的font设置的是13.5.大于原字体13.
UIFont *font=[UIFont fontWithName:@"PingFangSC-Regular" size:13.5];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:text];
//自定义str和TTTAttributedLabel一样的行间距
NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStyle alloc] init];
[paragrapStyle setLineSpacing:6];
//设置行间距
[attrString addAttribute:NSParagraphStyleAttributeName value:paragrapStyle range:NSMakeRange(0, text.length)];
//设置字体
[attrString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, text.length)];
CGFloat height = [TTTAttributedLabel sizeThatFitsAttributedString:attrString withConstraints:textSize limitedToNumberOfLines:0].height;
return height;
这样就轻松解决了cellheight的问题,总算保证了每行都能完整显示文字了。
由于我的项目上采用tableview方式显示文章内容,文字+图片,所以就遇到了这个问题,
以上是我想到的解决方法,分享一下,有需要的可以试试~