Adjust UIButton font size to width

adit picture adit · May 30, 2011 · Viewed 73.5k times · Source

I have the following code:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0.0, 0.0, 25, 25);

[[button layer] setCornerRadius:5.0f];
[[button layer] setMasksToBounds:YES];
[[button layer] setBackgroundColor:[[UIColor redColor] CGColor]];
[button.titleLabel setFrame:CGRectMake(0,0, 25, 25)];

[button setTitle:[NSString stringWithFormat:@"%@", [[topics objectAtIndex:indexPath.row] unread]] forState:UIControlStateNormal];

The issue is that when the string in the text is not long, it shows fine (1-2 digit). However, when it's quite long (3++ digit), all I can see is a red button, with no text inside. How do I adjust this?

I don't think that:

[button.titleLabel setAdjustsFontSizeToFitWidth:YES];

does the job, right?

Answer

elibud picture elibud · May 30, 2011

Try this:

button.titleLabel?.numberOfLines = 1
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.lineBreakMode = .byClipping //<-- MAGIC LINE

I'm not sure why this does the trick but it does :)