-
-
Save happyrobots/6618638 to your computer and use it in GitHub Desktop.
This file contains 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
@interface UILabel (Fit) | |
- (void)fitFontSize | |
@end |
This file contains 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
@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