简体   繁体   English

如何正确计算 NSMutableAttributedString 高度?

[英]How to calculate NSMutableAttributedString height correctly?

I have tried two methods:我尝试了两种方法:

attrString is NSMutableAttributedString attrStringNSMutableAttributedString

1. 1.

CGRect rect = [attrString boundingRectWithSize:CGSizeMake(contentWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attrString];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(contentWidth, CGFLOAT_MAX)];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
[layoutManager glyphRangeForTextContainer:textContainer];
CGRect rect = [layoutManager usedRectForTextContainer:textContainer];

But neither are right height.但两者都不是正确的高度。

Here is the demo: AttrStringDemo这是演示: AttrStringDemo

I plus 1 to height after calculated the rect, it works.在计算矩形后,我将高度加 1 ,它可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM