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

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

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

有什么建议吗?


当前回答

如果你只需要改变大小(Swift 4.0):

button.titleLabel?.font = button.titleLabel?.font.withSize(12)

其他回答

您应该遍历titleLabel属性。

button.titleLabel.font

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

对于Swift 3.0:

button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)

其中“boldSystemFont”和“16”可以替换为您的自定义字体和大小。

我们可以像下面这样使用不同类型的系统字体

myButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
myButton.titleLabel?.font = UIFont.italicSystemFont(ofSize:UIFont.smallSystemFontSize)
myButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: UIFont.buttonFontSize)

和你的自定义字体如下

    myButton.titleLabel?.font = UIFont(name: "Helvetica", size:12)

正如很多人在这里提到的,你可以设置字体如下:

button.titleLabel?.font = .systemFont(ofSize: 19.0, weight: .bold)

只要确保你的按钮有默认的样式就可以了,否则上面的内容会被系统忽略。

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

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