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

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

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

有什么建议吗?


当前回答

斯威夫特5

myButton.titleLabel?.font = UIFont(name: "yourCustomFont", size: CGFloat(yourFontSize))

其他回答

您不需要强制打开titleLabel来设置它。

myButton.titleLabel ?。字体= UIFont(名称:YourfontName,大小:20)

因为你没有在这里使用titleLabel,你可以选择使用它,如果它是nil,它将只是一个无操作。

我还将添加其他人所说的,字体属性已弃用,并确保在设置标题文本时使用setTitle:forControlState:。

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

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

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

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

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

斯威夫特5

myButton.titleLabel?.font = UIFont(name: "yourCustomFont", size: CGFloat(yourFontSize))

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

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

否则,你将使用:

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