0

I have several UIButton's together, and I want to adjust the font size so that it fits. However, each button should use the same font size so that they look the same. In other words, what I would like to do is set all button to the same minimum size.

_button1.titleLabel.adjustsFontSizeToFitWidth = YES;
_button2.titleLabel.adjustsFontSizeToFitWidth = YES;
float minFont1 = _button1.titleLabel.font.pointSize;
float minFont2 = _button2.titleLabel.font.pointSize;
float fontSize = MIN(minFont1, minFont2);
UIFont *tailoredFont = [_button1.titleLabel.font fontWithSize:fontSize];
_button1.titleLabel.font = tailoredFont;
_button2.titleLabel.font = tailoredFont;

However, this does not work because the titleLabel.font does not reflect the true size of the font.

4

1 回答 1

1

我最终采用的方法是找出每个按钮的理想字体大小,然后将所有按钮设置为最小的大小。

- (float)idealFontSizeForButton:(UIButton *)button
{
    UILabel *label = button.titleLabel;
    float width = button.bounds.size.width - 10;
    assert(button.bounds.size.width >= label.bounds.size.width);
    CGFloat actualFontSize;
    [label.text sizeWithFont:label.font
                minFontSize:label.minimumFontSize
             actualFontSize:&actualFontSize
                   forWidth:width
              lineBreakMode:label.lineBreakMode];
    debug(@"idealFontSizeForButton %f", actualFontSize);
    return actualFontSize;
}

……

// Set text and make sure both buttons have the same font size
[_button1 setTitle:title1 forState:UIControlStateNormal];
[_button2 setTitle:title2 forState:UIControlStateNormal];
float minFont1 = [self idealFontSizeForButton:_button1];
float minFont2 = [self idealFontSizeForButton:_button2];
float fontSize = MIN(minFont1, minFont2);
UIFont *tailoredFont = [_button1.titleLabel.font fontWithSize:fontSize];
_button1.titleLabel.font = tailoredFont;
_button2.titleLabel.font = tailoredFont;
于 2013-06-19T00:14:32.427 回答