adit adit - 1 year ago 110
Objective-C Question

adjust UIButton font size to width

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 Source

Try this:

button.titleLabel.numberOfLines = 1;
button.titleLabel.adjustsFontSizeToFitWidth = YES;
button.titleLabel.lineBreakMode = NSLineBreakByClipping; <-- MAGIC LINE

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download