3

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

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Rawr
  • 2,206
  • 3
  • 25
  • 53
  • Your question is vague about what your true problem is. Do you simply have a need to have a collection of `IBOutlet`s? Or are you have trouble actually using the `IBOutlet`? I say this because outlets **ARE** programmatic. – allenh Jul 09 '17 at 14:18
  • Yea I've slightly rephrased the question and edited it to better describe the goal I'm trying to achieve. I'm looking for an identifier that I can use to programatically access a variable (in this case an IBOutlet). – Rawr Jul 09 '17 at 14:32

3 Answers3

4

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!"
}
allenh
  • 6,582
  • 2
  • 24
  • 40
2

Swift 5 version:

if let aLabel = value(forKey: "label1") as? UILabel {
    aLabel.text = "Hello World"
}
סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68
1

There is a easier way to achieve your goal. First in your viewDidLoad, give yout outlet a unique tag number, other than 0

label1.tag = 1

Then, whenever you want to access it

if let theLabel = self.view.viewWithTag(1) as? UILabel {
    theLabel.text = "hello, world!"
}
Fangming
  • 24,551
  • 6
  • 100
  • 90
  • 1
    Tags are a very fragile way of identifying elements in a view hierarchy. They should be avoided. – allenh Jul 09 '17 at 14:16
  • This is the kind of solution I was looking for, is there an alternative that is less fragile? Looking for some kind of identifier to access an IBOutlet. In my original question I was hoping to access the variable by the name of the variable itself, but a tag like this answer would have been a viable alternative. – Rawr Jul 09 '17 at 14:30
  • @Rawr I think this is the only way that match your requirments. Yes using tag is not good but if you know what you are doing and you have **only one** tag system in your view controller, I see no harm of using it :) – Fangming Jul 09 '17 at 14:35