【问题标题】:UIButton not resizing fontsize automaticallyUIButton 不会自动调整字体大小
【发布时间】:2012-08-25 18:46:03
【问题描述】:

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

此代码不起作用(字体始终相同):

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

【问题讨论】:

  • 看看这个为我做的stackoverflow.com/questions/6178545/…
  • 还可以尝试在按钮的 titleLabel 上调用 sizeToFit 方法。
  • 你想要什么行为?您是希望文本扩展以适合按钮,您是希望按钮缩小以适合文本,还是希望文本缩小而不是被剪裁,如果它太大以适合?

标签: ios objective-c fonts uibutton


【解决方案1】:

代码有效,但可能不是您想要的方式。 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);
}

【讨论】:

  • 安德,你的代码就像一个魅力,非常感谢你!!!我仍然遇到的唯一问题是,更改按钮的内容(文本)时,它会将自身重新定位在按钮内的上方或下方,而不是保持居中。似乎起始位置也受到初始字体大小的影响,即使稍后调整它也是如此。我已经尝试 setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter 但它似乎没有做任何事情。
  • 代码工作..!!我想更新 :: 使用 'minimumScaleFactor' 而不是 'minimumFontSize' 因为它已被弃用。所以我们可以将最小字体大小设置为 -> myButton.titleLabel.minimumScaleFactor = 0.4; (40 / 100)。谢谢..:)
  • 感谢您的回答 - 正在寻找一种在 Storyboard 中创建的 UIButtons 上执行此操作的方法,其中它有针对 UILabel 但没有针对 UIButton 的设置。这确实可以按预期工作-是的,应该改用minimumScaleFactor
  • 如果您选择 UIButton 然后查看身份检查器,您可以在 Storyboard 中设置值。在“用户定义的运行时属性”下,输入要修改的键路径、类型和值。在这种情况下:titleLabelFontSizeToFitWidth, Boolean, Yes; titleLabel.minimumScaleFactor,数字,0.2。像魅力一样工作,无需添加代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-28
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 2011-02-28
  • 2011-02-07
  • 1970-01-01
相关资源
最近更新 更多