Created
May 9, 2019 09:49
-
-
Save remirobert/e09236f2cd108538b375eb2004792c01 to your computer and use it in GitHub Desktop.
NSAttributedString height calculation category
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@import CoreText; | |
@implementation NSAttributedString (Size) | |
- (CGFloat)heightForAttributedStringWithWidth:(CGFloat)inWidth { | |
if (self.length == 0) { | |
return 0; | |
} | |
NSTextStorage *textStorage = [[NSTextStorage alloc] | |
initWithAttributedString:self]; | |
NSTextContainer *textContainer = [[NSTextContainer alloc] | |
initWithSize: CGSizeMake(inWidth, FLT_MAX)]; | |
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init]; | |
[layoutManager addTextContainer:textContainer]; | |
[textStorage addLayoutManager:layoutManager]; | |
UIFont *font = [self attribute:NSFontAttributeName | |
atIndex:0 | |
longestEffectiveRange:nil | |
inRange:NSMakeRange(0, [textStorage length])]; | |
[textStorage | |
addAttribute:NSFontAttributeName value:font | |
range:NSMakeRange(0, [textStorage length])]; | |
[textContainer | |
setLineFragmentPadding:0.0]; | |
layoutManager.usesFontLeading = false; | |
[layoutManager | |
ensureGlyphsForGlyphRange:NSMakeRange(0, [textStorage length])]; | |
(void) [layoutManager | |
glyphRangeForTextContainer:textContainer]; | |
CGFloat height = [layoutManager | |
usedRectForTextContainer:textContainer].size.height; | |
return height; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment