我试图改变一个UIButton的字体使用Swift…

myButton.font = UIFont(name: "...", 10)

然而.font已弃用,我不确定如何改变字体,否则。

有什么建议吗?


当前回答

如果你将AttributedString设置为UIButton,那么你可以做下面的事情。

let attributedText = NSAttributedString(string: "Hello", attributes: [NSAttributedStringKey.font: UIFont(name: "Calibri", size: 19)])
okayButton.setAttributedTitle(attributedText, for: .normal)

其他回答

如果你将AttributedString设置为UIButton,那么你可以做下面的事情。

let attributedText = NSAttributedString(string: "Hello", attributes: [NSAttributedStringKey.font: UIFont(name: "Calibri", size: 19)])
okayButton.setAttributedTitle(attributedText, for: .normal)

您应该遍历titleLabel属性。

button.titleLabel.font

自iOS 3.0以来,字体属性已弃用。

如果你有字体大小的问题(你的字体没有响应大小的变化)…

@codester有正确的代码:

myButton.titleLabel!.font =  UIFont(name: YourfontName, size: 20)

然而,我的字体大小并没有改变。结果是我要求的字体并不存在(“HelveticaNeue-Regular”)。它并没有导致崩溃,但似乎只是因为它忽略了字体声明。一旦我将字体更改为一些确实存在的东西,更改为“size: x”确实呈现。

在Swift 5中,你可以利用点表示法来实现更快的语法:

myButton.titleLabel ?。font = .systemFont(ofSize: 14, weight: .medium)

否则,你将使用:

myButton.titleLabel ?。font = UIFont。systemFont(ofSize: 14, weight: .medium)

这适用于Swift 3.0:

btn.titleLabel?.font = UIFont(name:"Times New Roman", size: 20)