使用Swift在整个应用程序中更改UILabel的textColor

时间:2019-01-05 11:14:11

标签: ios swift uilabel

在Swift中我可以在整个应用程序中一次更改UILabel的文本颜色属性吗?我试过使用外观属性,但是不适用于UILabel textColor。可以在同一平台上运行的任何方式或任何库。

4 个答案:

答案 0 :(得分:6)

一种方法是使用颜色设置

从在xcassets目录中创建新集开始

enter image description here

...并按您的喜好命名

enter image description here

然后将颜色更改为所需的颜色

enter image description here

最后,从xcassets目录中将标签的颜色设置为此颜色

enter image description here enter image description here

...或以编程方式

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

现在,当您需要更改文本的颜色时,只需更改此颜色集

的颜色

答案 1 :(得分:0)

创建一个UILabel类,并将该类中的textColour设置为所需的颜色。并将该类赋予您在应用程序中使用的所有标签。如果要在会话期间更改所有标签的颜色(例如通过按钮操作),则可以为此使用NotificationCenter和Singleton。

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

https://cloud.google.com/appengine/docs/standard/java/config/webxml#filters

答案 2 :(得分:0)

AppDelegate.swift函数的didFinishLaunchingWithOptions中尝试此操作:

UILabel.appearance(whenContainedInInstancesOf: [UIView.self]).textColor = .red //or what color you want

答案 3 :(得分:0)

我真的很喜欢Arash Etemad's solution,但是发现它相当极端,因为它覆盖了所有颜色,即使其中一些颜色是自定义的。在处理现有的大型项目时,这不是很好。

所以我想到了这个(Swift 5.2):

extension UILabel {

    override open func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)

        guard newSuperview != nil else {
            return
        }

        if #available(iOS 13.0, *) {
            if textColor == UIColor.label {
                textColor = .red
            }
        } else if textColor == UIColor.darkText {
            textColor = .red
        }
    }    
}

它使用标签自身的生命周期事件来覆盖默认的系统字体颜色。随着iOS 13中暗模式的出现,可以将其标识为UIColor.label,而之前是UIColor.darkText

这可以防止覆盖自定义字体颜色(除非您的自定义颜色与默认的?!?相同),而无需在整个项目中手动设置字体颜色。