简体   繁体   中英

Overriding UILabel font causes cut off label

I'm creating a custom UILabel class. The reason why is because I want to adjust the properties of a Label with a Constants class. Modifying properties in IB can become cumbersome once the primary color of the app changes. Anyways this is my custom UILabel class:

@IBDesignable class FormTitleLabel: UILabel {

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

This causes the label to appear cut-off:

在此处输入图片说明

I can fix this by using the following code:

@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)
    }

}

Why does this solution work?

This code is simply wrong:

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

You're always returning font A , but internally setting font B . View drawing functions check the font of the label to draw text and they use font A , although in reality, they should use font B . That's why you have this weird behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM