Change UILabel's textColor in whole app using

2019-04-24 00:24发布

Is there any way in Swift i can change my UILabel's text color property at once in whole app? I've tried using appeareance property but that doesn't work for UILabel textColor. Any way or any library that works on the same.

3条回答
ら.Afraid
2楼-- · 2019-04-24 00:44

try this in your AppDelegate.swift inside didFinishLaunchingWithOptions function:

UILabel.appearance(whenContainedInInstancesOf: [UIView.self]).textColor = .red //or what color you want
查看更多
戒情不戒烟
3楼-- · 2019-04-24 00:51

One way is using Color Set.

Start with creating new set in your xcassets catalog

enter image description here

... and name it how you want to

enter image description here

Then change your color to color that you need

enter image description here

Finally, set color of your label as this color from xcassets catalog

enter image description here enter image description here

... or programmatically

label.textColor = UIColor(named: "ColorForLabel")

Now when you need to change color of text, just change color of this Color Set

查看更多
再贱就再见
4楼-- · 2019-04-24 00:52

Create a UILabel class and set the textColour in that class to your desired colour. And give this class to all the labels you are using in the app. If you want to change the colour of all labels during the session, say by button action, you can use NotificationCenter and Singleton for that purpose.

class LabelColor {
    static let shared = LabelColor()
    var color = UIColor.red
}

class ColoredLabel: UILabel {

    override func awakeFromNib() {
        super.awakeFromNib()
        textColor = LabelColor.shared.color
        NotificationCenter.default.addObserver(self, selector: #selector(self.changeColor(notification:)), name: Notification.Name(rawValue: "ChangeColor"), object: nil)
    }

    @objc func changeColor(notification: Notification) {
        let newColor = UIColor.blue
        textColor = newColor
        LabelColor.shared.color = newColor
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func changeColour(_ sender: UIButton) {
        NotificationCenter.default.post(name: Notification.Name("ChangeColor"), object: nil)
    }
}

StoryBoard

查看更多
登录 后发表回答