Skip to content

Instantly share code, notes, and snippets.

@remirobert
Created May 9, 2019 09:49
Show Gist options
  • Save remirobert/e09236f2cd108538b375eb2004792c01 to your computer and use it in GitHub Desktop.
Save remirobert/e09236f2cd108538b375eb2004792c01 to your computer and use it in GitHub Desktop.
NSAttributedString height calculation category
@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