UIAppearance not taking effect on UILabels created programmatically

前端 未结 5 1949
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-07 07:34

We have extended UILabel to be able to apply standard fonts and colors for all uses of a given label type in our apps. Eg.

@interface UILabelHeadingBold : UILab         


        
5条回答
  •  长情又很酷
    2021-02-07 08:34

    I was having this exact same issue, but in Swift. A custom UILabel's appearance would work if added from a storyboard, but not if added from code.

    Here's a solution I found in Swift that's working for me:

    class MyLabel: UILabel { }
    
    extension UILabel {
        @objc dynamic var customFont: UIFont! {
            get { return self.font }
            set { self.font = newValue }
        }
    
        @objc dynamic var customColor: UIColor! {
            get { return self.textColor }
            set {  self.textColor = newValue }
        }
    }
    

    Then add these lines where you configure your app appearance:

    MyLabel.appearance().customFont = UIFont.systemFont(ofSize: 20)
    MyLabel.appearance().customColor = UIColor.magenta
    

提交回复
热议问题