Raph
Raph

Reputation: 37

iOS/Swift 4: change color from a programmatically created label

I'm creating a several labels, based on the count of my array. And that works fine. But after some user interaction happens, I'd like to change the label color.

Here is my code:

-The array looks something like this:

var vids = [5: ["urltovideo1", "locationOne"], 7: ["urltovideo2", "locationTwo"]]

for label in vids[x][1] {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.backgroundColor = UIColor.gray
        label.text = vids[index[j] as! Int]![2]
        let z = CGFloat(j)
        self.view.addSubview(label)
        let horConstraint = NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 0.3+z, constant: 0.0)
        let verConstraint = NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 0.75, constant: 0.0)
        view.addConstraints([horConstraint, verConstraint])
}

-After the user interacts with the app, I try doing this:

for label in vids[x][1] {
    let label = UILabel()
    label.backgroundColor = UIColor.green
}

...but nothing happens.

Upvotes: 0

Views: 454

Answers (1)

Vyacheslav
Vyacheslav

Reputation: 27221

If you are doing namely this:

for label in vids[x][1] {
    let label = UILabel()
    label.backgroundColor = UIColor.green
}

Your labels will not be changed. The problem is that at line let label = UILabel() you just create a new instance of UILabel. This label is not the label you see on the iPhone screen.

One of the possible solutions.

Create somewhere in your class a storage of UILabels that you create in the first loop.

var vids = [5: ["urltovideo1", "locationOne"], 7: ["urltovideo2", "locationTwo"]]
var labels: [String: UILabel] = [:]

for labelString in vids[x][1] {
        let label = UILabel()
        labels[labelString] = label
        label.translatesAutoresizingMaskIntoConstraints = false
        label.backgroundColor = UIColor.gray
        label.text = vids[index[j] as! Int]![2]
        let z = CGFloat(j)
        self.view.addSubview(label)
        let horConstraint = NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 0.3+z, constant: 0.0)
        let verConstraint = NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 0.75, constant: 0.0)
        view.addConstraints([horConstraint, verConstraint])
}

and use it later:

for labelString in vids[x][1] {
    let label = labels[labelString] // < Here you retrieves a saved label
    label.backgroundColor = UIColor.green
}

Upvotes: 1

Related Questions