调整字体大小以适应几个UIButton,以便它们都具有相同的字体大小

时间:2013-06-07 17:57:41

标签: ios uibutton uilabel

我有几个UIButton,我想调整字体大小以适应它。但是,每个按钮应使用相同的字体大小,以使它们看起来相同。换句话说,我想要做的是将所有按钮设置为相同的最小尺寸。

_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;

但是,这不起作用,因为titleLabel.font不反映字体的真实大小。

1 个答案:

答案 0 :(得分: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;