我试图改变一个UIButton的字体使用Swift…
myButton.font = UIFont(name: "...", 10)
然而.font已弃用,我不确定如何改变字体,否则。
有什么建议吗?
我试图改变一个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)
其他回答
您应该遍历titleLabel属性。
button.titleLabel.font
自iOS 3.0以来,字体属性已弃用。
使用titleLabel代替。字体属性在iOS 3.0中已弃用。它也不能在Objective-C中工作。titleLabel是用于在UIButton上显示标题的标签。
myButton.titleLabel?.font = UIFont(name: YourfontName, size: 20)
然而,在设置标题文本时,你应该只使用setTitle:forControlState:。不要使用titleLabel直接为title设置任何文本。
对于Swift 3.0:
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
其中“boldSystemFont”和“16”可以替换为您的自定义字体和大小。
如果你将AttributedString设置为UIButton,那么你可以做下面的事情。
let attributedText = NSAttributedString(string: "Hello", attributes: [NSAttributedStringKey.font: UIFont(name: "Calibri", size: 19)])
okayButton.setAttributedTitle(attributedText, for: .normal)
在Swift 5中,你可以利用点表示法来实现更快的语法:
myButton.titleLabel ?。font = .systemFont(ofSize: 14, weight: .medium)
否则,你将使用:
myButton.titleLabel ?。font = UIFont。systemFont(ofSize: 14, weight: .medium)