Is it possible to use a variable in a label name.
For example, my label is called button1text
and I have a variable var x = 1
.
Is there a way to do thisbutton(x)text
?
Is it possible to use a variable in a label name.
For example, my label is called button1text
and I have a variable var x = 1
.
Is there a way to do thisbutton(x)text
?
Variable names are evaluated at compile time, so no, it's not possible (at runtime).
Alternatively use an array or assign tags to the labels and get the label with viewWithTag
You can use reflection with Mirror
. The capabilities are very limited in the context you want but you can try something like:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
@IBAction func didTapGoButton(_ sender: Any) {
let mirror = Mirror(reflecting: self)
for child in mirror.children {
if let v = child.label, v == "button2" {
(child.value as! UIButton).titleLabel?.text = "changed"
}
}
}
}