iOS: Font size to fit Label

Screen of tv guide menu, showing the fonts scaling to fill the buttons

I found a little snippet of code for resizing font sizes based on a UILabel size somewhere on the web (Sorry if it was your code, I couldn’t find the page again. But all credit to you!) The code below will take in a chunk of text, font name, minimum and maximum font size and a container size (width and height), and in return it will give you the font that will fit that space.

I have added the minimum and maximum constraints to the original version I found, just ensure that you don’t end up with a font thats too small to read, or bigger than you would like too see.


+(UIFont*)fontSizeForText:(NSString*)text fontName:(NSString*)fontname min:(int)min max:(int)max container:(CGSize)container{

UIFont *font = [UIFont fontWithName:fontname size:max];

int i;

for(i = max; i > min; i=i-2)
font = [font fontWithSize:i];

CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);

CGSize labelSize = [text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

if(labelSize.height <= container.height)

return font;

Leave a Comment

Time limit is exhausted. Please reload CAPTCHA.