Skip to content

Instantly share code, notes, and snippets.

@hermanccw
Created March 30, 2015 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hermanccw/3fbf5df207854d0191b4 to your computer and use it in GitHub Desktop.
Save hermanccw/3fbf5df207854d0191b4 to your computer and use it in GitHub Desktop.
- (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