覆盖 UILabel 字体会导致标签被截断

Overriding UILabel font causes cut off label

我正在创建自定义 UILabel class。之所以是因为我想调整一个Label的属性,有一个Constantsclass。一旦应用程序的主要颜色发生变化,在 IB 中修改属性会变得很麻烦。无论如何,这是我的自定义 UILabel class:

@IBDesignable class FormTitleLabel: UILabel {

    override var font: UIFont! {
        get {
            return UIFont.systemFont(ofSize: 36, weight: .heavy)
        } set {
            super.font = font
        }
    }
}

这会导致标签出现截断:

我可以使用以下代码解决此问题:

@IBDesignable class FormTitleLabel: UILabel {

    override var font: UIFont! {
        get {
            return UIFont.systemFont(ofSize: 36, weight: .heavy)
        } set {
            super.font = font
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        setup()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!

        setup()
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        setup()
    }

    private func setup() {
        self.font = UIFont.systemFont(ofSize: 36)
    }

}

为什么这个解决方案有效?

这段代码完全错误:

override var font: UIFont! {
    get {
        return UIFont.systemFont(ofSize: 36, weight: .heavy)
    } set {
        super.font = font
    }
}

您总是返回字体 A,但在内部设置字体 B。查看绘图函数检查标签的字体以绘制文本,它们使用字体 A,但实际上它们应该使用字体 B。这就是为什么你有这种奇怪的行为。