Steve
Steve

Reputation: 4985

Iterate through all labels in a static table view

I have a static tableViews and a button to change the colour scheme (theme) of the app. Is there a fast way for me to change all the label colours throughout the table from white to black? im thinking something like the following.

Pseudo code:

for subview in view.subviews {
   if subview is UILabel {
   subview.fontColor = .black
   }
}

So when the orange switch is on the "Light" side I would like all labels to go black. I have used story board to construct it, so it would be nice if I could avoid having to connect all labels to the .swift file.

enter image description here Light

Upvotes: 1

Views: 487

Answers (1)

Matloob Hasnain
Matloob Hasnain

Reputation: 1037

I am writing about code for your sudo code you need to iterate with recursion.

func getLabelsInView(view: UIView) -> [UILabel] {
    var results = [UILabel]()
    for subview in view.subviews as [UIView] {
        if let label = subview as? UILabel {
            results += [label]
        } else {
            results += getLabelsInView(view: subview)
        }
    }
    return results
}

Call any where from you need to change color

let labels = getLabelsInView(self.view) // or any other view / table view
    for label in labels {
      label.textColor = .black
    }

Upvotes: 2

Related Questions