UITableView的动态获取高度 排版
大神请绕路~~~
最近做一款应用的界面,页面是图片,文字,头像,地址,时间等随机排列组成的。
这里简单记录,解决文字单独排版的解决方法,看了网上很多大神的博客分享内容。
刚开始,使用了最常见的方法:
在 cellForRowAtIndexPath 里面 赋值文字显示,
在 heightForRowAtIndexPath 里面使用Category如下:
- (CGSize)boundingRectWithSize:(CGSize)size
{
NSDictionary *attribute = @{NSFontAttributeName: self.font};
CGSize retSize = [self.text boundingRectWithSize:size
options:\
NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading
attributes:attribute
context:nil].size;
return retSize;
}
计算出这段文字的高度,加上cell上其他图片之类的高度,返回高度值。
应为cell上面的label是约束搞得 ,所以改变了cell得高度,label高度自然改变。
后来,设计师要求更改文字行间距,查询N久,解决方法如下:
NSString *cntentText = @“水电费水电费的说法”;
if (cntentText) {
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:cntentText];;
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
[paragraphStyle setLineSpacing:15];//行间距
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, cntentText.length)];
cell.concentText.attributedText = attributedString;
}
之后需要在 heightForRowAtIndexPath 中计算加了行间距此段文字的高度:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:detailContent];;
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
[paragraphStyle setLineSpacing:15];//和上面对应
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, detailContent.length)];
cell.concentText.attributedText = attributedString;
CGSize size1 = CGSizeMake(kDECEIVE_WIDTH - 16 - 16, 5000);
CGSize labelSize = [cell.concentText sizeThatFits:size1];
return labelSize.height + 20;//加上其他内容占据的空间大小返回
暂时解决,会继续想其他办法看能否简化下,可以需要支持iOS7,不能使用iOS8的cell自适应大小。
继续搬砖解决字间距段间距的问题。