大家在网上可能看到很多关于计算label高度的帖子,其中关于NSString的label高度是没有问题的,但是遇到label需要设置NSAttributeString的时候,计算就不准确了,我们看到系统对于NSAttributeString有一个计算cgrect的方法
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(NSStringDrawingContext *)context NS_AVAILABLE_IO
但是当我用该方法去计算以下这个NSAttributeString的高度时,总是不准确
NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:m.detail];
NSMutableParagraphStyle *paragraphstyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphstyle.lineSpacing = 5;
paragraphstyle.alignment = NSTextAlignmentRight;
paragraphstyle.lineBreakMode = kCTLineBreakByWordWrapping;
[attributeStr addAttribute:NSParagraphStyleAttributeName value:paragraphstyle range:NSMakeRange(0, [attributeStr length])];
最终发现使用UIView的sizeThatFits是可以的
NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:m.detail];
NSMutableParagraphStyle *paragraphstyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphstyle.lineSpacing = 5;
paragraphstyle.alignment = NSTextAlignmentRight;
paragraphstyle.lineBreakMode = kCTLineBreakByWordWrapping;
[attributeStr addAttribute:NSParagraphStyleAttributeName value:paragraphstyle range:NSMakeRange(0, [attributeStr length])];
self.timeDetailLabel.attributedText = attributeStr;
CGSize textSize = [self.orderVCTableViewCell.timeDetailLabel sizeThatFits:CGSizeMake(self.timeDetailLabel.frame.size.width, MAXFLOAT)];
但是该方法计算出来的height会变成2倍,暂时还没有发现为什么变成2倍了,以后发现会上来更新。