首页 文章

所有UILabel的默认文本颜色

提问于
浏览
8

我想为我的应用中的所有UILabel设置默认文本颜色 . 我找到了这个:

UILabel.appearance().textColor = UIColor.red

这有效,但是当我想在其故事板中为特定标签设置其他颜色时,它无法完成 - 所有标签仍然是红色的 .

是否可以通过在故事板中设置它来为所有UILabel定义默认文本颜色,然后在故事板(而不是代码)中为某些UILabel ALSO更改它?或者使用Appearance API在代码中设置默认颜色,并为storyboard中的某些标签更改它?

2 回答

  • 9

    还有穆罕默德所建议的替代方案 . 另一种方法是使用UIAppearance代理,但指定应用它的类 .

    在这种情况下,你会像这样使用它:

    UILabel.appearanceWhenContainedInInstancesOfClasses([MyViewController.self, MyotherViewController.self]).textColor = UIColor.red
    

    上面的,只允许你在某些类中设置textColor你自己 . 在代理设置为启用的那些中,您将无法设置文本颜色 .

    由您决定哪种方法更适合您的情况

  • 2

    使用CustomLabel.swift标记的子类 . 您可以使用名为 txtColorIBDesignable 属性设置文本颜色

    下面是代码工作示例

    import UIKit
    
        @IBDesignable  class CustomLabel: UILabel {
    
            @IBInspectable var txtColor: UIColor = UIColor.grayColor() {
                didSet {
                    self.textColor = txtColor
                }
            }
    
            func setup() {
               self.textColor = txtColor
            }
    
            override func awakeFromNib() {
                setup()
            }
    
            override func prepareForInterfaceBuilder() {
                setup()
            }
    
        }
    

相关问题