![](/img/trans.png)
[英]How to adjust font size of text in a UIButton to fit the width programmatically in Swift?
[英]Adjust font size of text to fit in UIButton
我想确保按钮文本适合 UIButton,而 UIButton 具有固定大小。
当然我可以访问 UIButton 的 titleLabel。 在标签中,我将自动autoshrink
设置为最小字体比例,这似乎对应于
self.myButton.titleLabel.adjustsFontSizeToFitWidth = YES;
,但实际上并不相同,因为它只会使文本水平地适合边界,而不是垂直地,因此不会改变字体大小。
我如何以编程方式实际调整标签的字体大小以使文本适合标签边界(如下图的目标所示)?
我已经试过了
self.myButton.titleLabel.numberOfLines = 0;
self.myButton.titleLabel.minimumScaleFactor = 0.5f;
没有成功,总是像上图左侧的adjustsFontSizeToFitWidth
一样结束。
编辑:该解决方案还必须与 ios7 兼容
self.mybutton.titleLabel.minimumScaleFactor = 0.5f;
self.mybutton.titleLabel.numberOfLines = 0; <-- Or to desired number of lines
self.mybutton.titleLabel.adjustsFontSizeToFitWidth = YES;
... 在 viewDidLoad 中的 layoutIfNeeded 之后,成功了,事实证明,所有这些都必须设置为实际调整字体大小,而不仅仅是使其适合框架。
mybutton.titleLabel?.minimumScaleFactor = 0.5
mybutton.titleLabel?.numberOfLines = 0 <-- Or to desired number of lines
mybutton.titleLabel?.adjustsFontSizeToFitWidth = true
您还可以在 Interface Builder 中为按钮设置用户定义的运行时属性,其中
titleLabel.adjustsFontSizeToFitWidth = true
Swift 3.0 的更新代码:
yourButton.titleLabel?.minimumScaleFactor = 0.5
yourButton.titleLabel?.numberOfLines = 0
yourButton.titleLabel?.adjustsFontSizeToFitWidth = true
使文本水平和垂直适合按钮边界:
1 - 像图像一样设置按钮对齐(* 非常重要 *)
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。 用于在按钮中启用多行。 只是使用上面的代码最后结果 :
尝试调用以下方法。
button.titleLabel?.baselineAdjustment = UIBaselineAdjustment.AlignCenters
尝试这个:
[myButton setFont:[[myButton font] fontWithSize:--originalButtonFontSize]];
textWidth = [text sizeWithFont:[myButton font]].width;
}
在Xcode->打开故事板->转到属性检查器->控制->对齐->在水平和垂直中选择第二个。
或者
YourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
在代码后面写下这一行:
yourButton.SizeToFitWidth=YES;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.