Search code examples
swiftiboutlet

Get an outlet variable by name


Looking for a way to access an outlet programmatically in swift:

@IBOutlet var label1: UILabel?
var outletName = "label1"
view[outletName].text = "hello, world!"

Is the only way to do this to create my own custom mapping, like so?

@IBOutlet var label1: UILabel?
let outlets = ["label1": label1]
let outletName = "label1"
outlets[outletName].text = "hello, world!"

EDIT: Seems my original question was poorly worded, lets try again:
I'm looking to access a variable through some string identifier. In my original question I was trying to ask if a variable can be accessed by the name of the variable itself somehow. IE accessing variable label1 with a string of the variable's name "label1".


Solution

  • Turning a string into a property access is actually kind of difficult in pure Swift.

    You can use some objective-c APIs to help you out.

    // Mark your outlet variable as dynamic
    @IBOutlet dynamic var label1: UILabel?
    
    var outletName = "label1"
    // Then you can access it via a key path (aka string)
    if let myProperty = value(forKey: outletName) as? UILabel {
        myProperty.text = "Hello, world!"
    }