L.Goyal
L.Goyal

Reputation: 895

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 OBJ-C. I do not know the code and am working in SWIFT so please can anyone explain and translate this code in swift. I am still new to swift so please help me.

Regards

Upvotes: 0

Views: 1425

Answers (3)

ilija.trkulja
ilija.trkulja

Reputation: 147

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

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100549

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

Upvotes: 2

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.

Upvotes: 0

Related Questions