flip79 flip79 - 5 months ago 17
iOS Question

UIButton not resizing fontsize automatically

I'm programmatically adding a UIButton to my view, and I want that font size into the button resize it automatically (e.g. if the text is long, resize to a smaller font to fit the button).

This code is not working (the font is always the same):

myButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];
[myButton setTitle:[NSString stringWithFormat:@"hello"] forState:UIControlStateNormal];
[myButton setFrame: CGRectMake(0, 0, 180, 80)];
[myButton.titleLabel setFont: [UIFont boldSystemFontOfSize:16.0]];

myButton.titleLabel.adjustsFontSizeToFitWidth = TRUE;

[theView addSubview:myButton];

Answer

The code works, but perhaps not in the way you want it to. The adjustsFontSizeToFitWidth property only ever reduces the font size if the text won't fit (down to the minimumFontSize). It will never increase the font size. In this case, a 16pt "hello" will easily fit in the 180pt wide button so no resizing will occur. If you want the font to increase to fit the space available you should increase it to a large number so that it will then be reduced to the maximum size that fits.

Just to show how it's currently working, here's a nice contrived example (click on the button to reduce its width as see the font reduce down to the minimumFontSize):

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *myButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];
    [myButton setTitle:[NSString stringWithFormat:@"hello"] forState:UIControlStateNormal];
    [myButton setFrame: CGRectMake(10, 10, 300, 120)];
    [myButton.titleLabel setFont: [UIFont boldSystemFontOfSize:100.0]];
    myButton.titleLabel.adjustsFontSizeToFitWidth = YES;
    myButton.titleLabel.minimumFontSize = 40;
    [myButton addTarget:self action:@selector(buttonTap:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:myButton];
}

- (void)buttonTap:(UIButton *)button {
    button.frame = CGRectInset(button.frame, 10, 0);
}