Skip to content

Instantly share code, notes, and snippets.

Created September 19, 2013 02:49
Show Gist options
  • Save anonymous/6618560 to your computer and use it in GitHub Desktop.
Save anonymous/6618560 to your computer and use it in GitHub Desktop.
@interface UILabel (Fit)
- (void)fitFontSize
@end
@implementation UILabel (Fit)
- (void)fitFontSize
{
UIFont *font = self.font;
NSInteger maxFontSize = font.pointSize;
CGFloat width = CGRectGetWidth(self.frame);
CGFloat height = CGRectGetHeight(self.frame);
CGSize constraintSize = CGSizeMake(width, CGFLOAT_MAX);
for (NSInteger i = maxFontSize; i >= self.minimumFontSize; i--) {
font = [font fontWithSize:i];
CGSize expectedLabelSize = [self.text sizeWithFont:font
constrainedToSize:constraintSize];
if (expectedLabelSize.height <= height)
break;
}
self.font = font;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment