Ios 调整字体大小以适合多个UIButton';因此,它们都有相同的字体大小

Ios 调整字体大小以适合多个UIButton';因此,它们都有相同的字体大小,ios,uibutton,uilabel,Ios,Uibutton,Uilabel,我有几个ui按钮,我想调整字体大小使其适合。但是,每个按钮应使用相同的字体大小,以便它们看起来相同。换句话说,我想做的是将所有按钮设置为相同的最小大小 _button1.titleLabel.adjustsFontSizeToFitWidth = YES; _button2.titleLabel.adjustsFontSizeToFitWidth = YES; float minFont1 = _button1.titleLabel.font.pointSize; float minFont2

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

_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不能反映字体的真实大小

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

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