简体   繁体   中英

How to change the color of all Labels in a UIView in Swift?

I found a similar question here . But the problem is it is in .I do not know the code and am working in so please can anyone explain and translate this code in swift.工作,所以请任何人都可以快速解释和翻译此代码。 I am still new to swift so please help me.

Regards

Create

var globalColor = UIColor.red

class CustomLbl:UILabel {
  override func awakeFromNib() {  // inside IB
    super.awakeFromNib()
    self.textColor = globalColor
  }
  override func draw(_ rect: CGRect) { // programmatically 
     super.draw(rect)
     self.textColor = globalColor
  }
}

And assign it in IB or code , for programmatically call

self.view.setNeedsDisplay()

after you change global color

with an extension. Maybe its not the perfect solution but once you applied it to all needed labels, then it applies to all labels when you make a change. Create a new swift file and put the following code in:

    import UIKit

extension UILabel {
    func labelColor() {
        self.textColor = UIColor.red //or whichever color you want
    }
}

And in the viewDidLoad or viewWillLoad you can do:

yourLabel.labelColor()
self.view.subviews.forEach { (view) in    // Loop
     if let label = view as? UILabel {    // check the type
          label.textColor = .red          // assign the color
     }
}

And self is your viewController

As explain in the similar question, you have to

Loop through all the UIView's in self.view.subviews and check if it's of type UILabel.

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