ios UIButton 不会自动调整字体大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12207050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UIButton not resizing fontsize automatically
提问by flip79
I'm programmatically adding a UIButton to my view, and I want that font size into the button resize it automatically (e.g. if the text is long, resize to a smaller font to fit the button).
我正在以编程方式将 UIButton 添加到我的视图中,并且我希望按钮中的字体大小自动调整其大小(例如,如果文本很长,则调整为较小的字体以适合按钮)。
This code is not working (the font is always the same):
此代码不起作用(字体始终相同):
myButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];
[myButton setTitle:[NSString stringWithFormat:@"hello"] forState:UIControlStateNormal];
[myButton setFrame: CGRectMake(0, 0, 180, 80)];
[myButton.titleLabel setFont: [UIFont boldSystemFontOfSize:16.0]];
myButton.titleLabel.adjustsFontSizeToFitWidth = TRUE;
[theView addSubview:myButton];
回答by Ander
The code works, but perhaps not in the way you want it to. The adjustsFontSizeToFitWidth
property only ever reduces the font size if the text won't fit (down to the minimumFontSize
). It will never increase the font size. In this case, a 16pt "hello" will easily fit in the 180pt wide button so no resizing will occur. If you want the font to increase to fit the space available you should increase it to a large number so that it will then be reduced to the maximum size that fits.
该代码有效,但可能不是您想要的方式。adjustsFontSizeToFitWidth
如果文本不适合(直到minimumFontSize
),该属性只会减小字体大小。它永远不会增加字体大小。在这种情况下,一个 16pt 的“hello”很容易放入 180pt 宽的按钮中,因此不会发生大小调整。如果您希望字体增加以适应可用空间,则应将其增加到一个较大的数字,以便将其减小到适合的最大大小。
Just to show how it's currently working, here's a nice contrived example (click on the button to reduce its width as see the font reduce down to the minimumFontSize
):
只是为了展示它当前的工作方式,这是一个很好的人为示例(单击按钮以减小其宽度,看到字体减小到minimumFontSize
):
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *myButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];
[myButton setTitle:[NSString stringWithFormat:@"hello"] forState:UIControlStateNormal];
[myButton setFrame: CGRectMake(10, 10, 300, 120)];
[myButton.titleLabel setFont: [UIFont boldSystemFontOfSize:100.0]];
myButton.titleLabel.adjustsFontSizeToFitWidth = YES;
myButton.titleLabel.minimumFontSize = 40;
[myButton addTarget:self action:@selector(buttonTap:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:myButton];
}
- (void)buttonTap:(UIButton *)button {
button.frame = CGRectInset(button.frame, 10, 0);
}