gpt4 book ai didi

ios - UIButton 不自动调整字体大小

转载 作者:IT王子 更新时间:2023-10-29 07:57:27 25 4
gpt4 key购买 nike

我正在以编程方式将 UIButton 添加到我的 View 中,我希望按钮中的字体大小会自动调整它的大小(例如,如果文本很长,请调整为较小的字体以适合按钮)。

此代码无效(字体始终相同):

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

最佳答案

代码有效,但可能不是您想要的方式。 adjustsFontSizeToFitWidth 属性只会在文本不适合时减小字体大小(减小到 minimumFontSize)。它永远不会增加字体大小。在这种情况下,一个 16pt 的“hello”很容易适合 180pt 宽的按钮,因此不会发生调整大小。如果您希望字体增加以适应可用空间,您应该将其增加到一个较大的数字,这样它就会缩小到适合的最大尺寸。

只是为了展示它当前是如何工作的,这里有一个很好的设计示例(单击按钮以减小其宽度,因为看到字体减小到 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);
}

关于ios - UIButton 不自动调整字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12207050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com