Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an outlet variable by name

Tags:

swift

iboutlet

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".

like image 469
Rawr Avatar asked Apr 07 '26 22:04

Rawr


2 Answers

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!"
}
like image 52
allenh Avatar answered Apr 10 '26 11:04

allenh


Swift 5 version:

if let aLabel = value(forKey: "label1") as? UILabel {
    aLabel.text = "Hello World"
}
like image 43
Türker Güney Avatar answered Apr 10 '26 10:04

Türker Güney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!