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

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

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

有什么建议吗?


当前回答

这适用于Swift 3.0:

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

其他回答

您应该遍历titleLabel属性。

button.titleLabel.font

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

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

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

要使用故事板完成此操作,请在选中按钮时转到属性检查器。在顶部的第三个字段(“标题”)选择“已归属”。这将弹出字体下拉列表,您可以轻松更改字体。

例子:button.titleLabel ?。font = UIFont(名称:"HelveticaNeue-Bold",字号:12)

如果你想使用它自己家族的默认字体,使用例如:"HelveticaNeue" 如果你想指定家族字体,使用例如:"HelveticaNeue-Bold"

使用titleLabel代替。字体属性在iOS 3.0中已弃用。它也不能在Objective-C中工作。titleLabel是用于在UIButton上显示标题的标签。

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

然而,在设置标题文本时,你应该只使用setTitle:forControlState:。不要使用titleLabel直接为title设置任何文本。