调整文字的字体大小以适应UIButton

时间:2015-09-14 09:31:16

标签: ios objective-c swift uibutton uilabel

我想确保按钮文本适合UIButton,而UIButton具有固定大小。

当然,我可以访问UIButton的titleLabel。 在标签中,我会将autoshrink设置为最小字体比例,这似乎与

相对应
self.myButton.titleLabel.adjustsFontSizeToFitWidth = YES;

,但实际上并没有相同的行为,因为它只会使文本水平地适合边界,而不是垂直,从而不会改变字体大小。

如何以编程方式实际调整标签的字体大小以使文本适合标签边界(如下图中目标所示)?

adjustsFontSizeToFitWidth does not actually adjust the font size to fit the frame, only the width

我已经尝试了

self.myButton.titleLabel.numberOfLines = 0;
self.myButton.titleLabel.minimumScaleFactor = 0.5f;

没有成功,总是在上面图片左侧的adjustsFontSizeToFitWidth中结束。

修改解决方案还必须符合ios7

9 个答案:

答案 0 :(得分:75)

self.mybutton.titleLabel.minimumScaleFactor = 0.5f;
self.mybutton.titleLabel.numberOfLines = 0;   <-- Or to desired number of lines
self.mybutton.titleLabel.adjustsFontSizeToFitWidth = YES;

...在viewDidLoad中的layoutIfNeeded之后完成了这个技巧 事实证明,所有这些必须设置为实际调整字体大小,而不仅仅是使其适合框架。

Swift 3更新:

mybutton.titleLabel?.minimumScaleFactor = 0.5
mybutton.titleLabel?.numberOfLines = 0   <-- Or to desired number of lines
mybutton.titleLabel?.adjustsFontSizeToFitWidth = true

答案 1 :(得分:7)

更新了Swift 3.0的代码:

href="/watch?v=8M00cos0d_0"

答案 2 :(得分:6)

您还可以在Interface Builder中为按钮

设置用户定义的运行时属性
titleLabel.adjustsFontSizeToFitWidth = true

答案 3 :(得分:3)

尝试调用以下方法。

button.titleLabel?.baselineAdjustment = UIBaselineAdjustment.AlignCenters

答案 4 :(得分:1)

try this:

  [myButton setFont:[[myButton font] fontWithSize:--originalButtonFontSize]];
  textWidth = [text sizeWithFont:[myButton font]].width;

}

答案 5 :(得分:0)

使文本在水平和垂直方向上都适合按钮范围:

1-像图像一样设置按钮对齐方式(*非常重要*)

enter image description here

2-在您的ViewController中添加以下代码行

btnTest.setTitle("Test for multi line in button show line in button show Test for multi line in button show line in button show", for: .normal)
btnTest.titleLabel!.textAlignment = .center
btnTest.titleLabel!.numberOfLines = 0
btnTest.titleLabel!.adjustsFontSizeToFitWidth = true
btnTest.titleLabel!.minimumScaleFactor = 0.5
// below line to add some inset for text to look better
// you can delete or change that
btnTest.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  • 请注意不要在代码中使用btnTest.titleLabel!.lineBreakMode = NSLineBreakMode.byWordWrapping或其他BreakMode。用于启用按钮中的多行。只是从上面的代码中使用

最终结果:

enter image description here

答案 6 :(得分:0)

在 Storyboard 中,转到 Attributes Inspector 中的 Link Break,查看自动换行...或根据您的选择进行设置。

答案 7 :(得分:-2)

在代码后面写下这一行:

yourButton.SizeToFitWidth=YES;

答案 8 :(得分:-3)

如果您更喜欢在故事板中进行操作,只需单击按钮,然后显示属性检查器,并将换行符设置为&#34; Word Wrap&#34;。

word wrap