簡體   English   中英

調整字體大小以適合多個UIButton,以使它們都具有相同的字體大小

[英]Adjust the font size to fit for several UIButton's so that they all have the same font size

我有幾個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不能反映字體的真實大小。

我最終采用的方法是找出每個按鈕的理想字體大小,然后將所有按鈕設置為最小字體。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM