Last active
December 24, 2015 20:29
-
-
Save zaneclaes/6858191 to your computer and use it in GitHub Desktop.
How to measure text on both iPhone and OSX (sizeWithFont for OSX)
This file contains hidden or 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
// 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