调整字体大小以适合多个 UIButton,使它们都具有相同的字体大小 [英] Adjust the font size to fit for several UIButton's so that they all have the same font size

查看:52
本文介绍了调整字体大小以适合多个 UIButton,使它们都具有相同的字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

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

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

推荐答案

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

The approach I ended up taking is to figure out the ideal font size for each button, and then setting all of the buttons to the smallest of the sizes.

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

这篇关于调整字体大小以适合多个 UIButton,使它们都具有相同的字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆