Skip to content

Instantly share code, notes, and snippets.

@happyrobots
Forked from anonymous/UILabel+Fit.h
Created September 19, 2013 03:02
Show Gist options
  • Save happyrobots/6618638 to your computer and use it in GitHub Desktop.
Save happyrobots/6618638 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 = constraintSize;
if ([self.text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
// iOS 7
expectedLabelSize = [self.text boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName: font}
context:nil].size;
} else {
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