Search code examples
swiftvariablesuibuttonuilabel

Variable UILabel name


Is it possible to make a label as a variable? I have multiple labels:

@IBOutlet weak var FL1at0: UIButton!
@IBOutlet weak var FL1at3: UIButton!
@IBOutlet weak var FL1at6: UIButton!
@IBOutlet weak var FL1at9: UIButton!
@IBOutlet weak var FL1at12: UIButton!
@IBOutlet weak var FL1at15: UIButton!
@IBOutlet weak var FL1at18: UIButton!
@IBOutlet weak var FL1at21: UIButton!

Sample Function:

       else
       {
           UserDefaults.standard.set(true, forKey: "RedFl1")
           self.FL1at0.setTitleColor(UIColor.red, for: .normal); self.ProgressUpdate()
       }

Is there a way to set the table in a way to work like this:

self.FL1at"\(TimeStamp)".setTitleColor(UIColor.red, for: .normal)//TimeStamp comes from function

Solution

  • Try this:

    let dict: Dictionary<String, UIButton> = ["FL1at0": FL1at0, "FL1at3": FL1at3, ...]
    let x = "FL1at\(TimeStamp)"
    if let y = dict[x] as? UIButton {
        y.setTitleColor(UIColor.red, for: .normal)
    }