Created
March 30, 2015 19:28
-
-
Save hermanccw/3fbf5df207854d0191b4 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
- (void)adjustFontSizeToFit | |
{ | |
UIFont *font = self.font; | |
CGSize size = self.frame.size; | |
for (CGFloat maxSize = self.font.pointSize; maxSize >= self.minimumFontSize; maxSize -= 1.f) | |
{ | |
font = [font fontWithSize:maxSize]; | |
CGSize constraintSize = CGSizeMake(size.width, MAXFLOAT); | |
NSString *text = self.text; | |
if ([text isEmptyAfterTrimmed]) { | |
text = self.placeholder; | |
} | |
CGRect labelSize = [text boundingRectWithSize:constraintSize | |
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine) | |
attributes:@{NSFontAttributeName:font} | |
context:nil]; | |
// Keeping the width constant if given text requires more height , decrease the font size. | |
if(labelSize.size.height <= size.height) | |
{ | |
self.font = font; | |
[self setNeedsLayout]; | |
break; | |
} | |
} | |
// set the font to the minimum size anyway | |
self.font = font; | |
[self setNeedsLayout]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment