Skip to content

Instantly share code, notes, and snippets.

@rolandkakonyi
Created July 17, 2018 08:42
Show Gist options
  • Save rolandkakonyi/042b9eec74a2dd9395e2fced177694a2 to your computer and use it in GitHub Desktop.
Save rolandkakonyi/042b9eec74a2dd9395e2fced177694a2 to your computer and use it in GitHub Desktop.
UILabel auto font size
- (void)resizeFontForLabel:(UILabel*)aLabel maxSize:(int)maxSize minSize:(int)minSize lblWidth: (float)lblWidth lblHeight: (float)lblHeight {
// use font from provided label so we don't lose color, style, etc
UIFont *font = aLabel.font;
// start with maxSize and keep reducing until it doesn't clip
for(int i = maxSize; i >= minSize; i--) {
font = [font fontWithSize:i];
CGSize constraintSize = CGSizeMake(lblWidth, MAXFLOAT);
// NSString* string = [aLabel.text stringByAppendingString:@"..."];
CGSize labelSize = [aLabel.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:aLabel.lineBreakMode];
if(labelSize.height <= lblHeight)
break;
}
// Set the UILabel's font to the newly adjusted font.
aLabel.font = font;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment