Created
July 17, 2018 08:42
-
-
Save rolandkakonyi/042b9eec74a2dd9395e2fced177694a2 to your computer and use it in GitHub Desktop.
UILabel auto font size
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)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