简体   繁体   中英

How to calculate NSMutableAttributedString height correctly?

I have tried two methods:

attrString is NSMutableAttributedString

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

I plus 1 to height after calculated the rect, it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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