Skip to content

Instantly share code, notes, and snippets.

@zaneclaes
Last active December 24, 2015 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaneclaes/6858191 to your computer and use it in GitHub Desktop.
Save zaneclaes/6858191 to your computer and use it in GitHub Desktop.
How to measure text on both iPhone and OSX (sizeWithFont for OSX)
// Part of a category on NSString...
- (CGSize)sizeWithFontName:(NSString*)fontName ofSize:(float)size constrainedTo:(CGSize)constraint {
#ifdef __CC_PLATFORM_MAC
NSFont *font = [NSFont fontWithName:fontName size:size];
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:self];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:constraint];
;
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
[textStorage addAttribute:NSFontAttributeName value:font
range:NSMakeRange(0, [textStorage length])];
[textContainer setLineFragmentPadding:0.0];
(void) [layoutManager glyphRangeForTextContainer:textContainer];
return [layoutManager
usedRectForTextContainer:textContainer].size;
#elif defined(__CC_PLATFORM_IOS)
UIFont * font = [UIFont fontWithName:fontName size:size];
return [self sizeWithFont:font constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
#endif
return CGSizeZero;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment