在我的代码中,我创建了一个自定义按钮(即UIButton的子类(,但我无法为按钮设置字体。已经观察到,如果我使用self.titleLabel?.text = title
,它工作得很好,但每当我使用方法self.setTitle(title, for: .normal)
字体时,都会重置为系统字体。我需要这个字体来显示按钮的所有状态,所以我必须使用函数setTitle
。我的自定义按钮代码如下
class RoundedButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
styleButton()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
styleButton()
}
func styleButton(title: String = "button", font: UIFont = .customFont16) {
self.setTitle(title, for: .normal)
self.backgroundColor = UIColor.yellow
titleLabel?.font = font
}
}
您可以在自定义类中添加用于设置字体的变量。然后从viewController设置字体。
var titleFont: UIFont = UIFont.preferredFont(forTextStyle: .footnote) {
didSet {
titleLabel?.font = titleFont
}
}
将上面的代码添加到您的自定义类中,并在viewController中访问它,如下所示。
@IBOutlet weak var roundButton: RoundedButton!
override func viewDidLoad() {
super.viewDidLoad()
roundButton.titleFont = .caption1
}