TPCO
TPCO

Reputation: 301

How to use a variable's value as a UILabel?

I have 6 UILabels as IBOutlets named tutorialLabel1, tutorialLabel2, etc... I want to bring them all to front using a loop. Here is my code:

var tempLabel = "tutorialLabel"
for var i=1; i<=6; i++ {
    tempLabel = "tutorialLabel" + String(i)
    self.tempLabel.bringSubviewToFront(self.tempLabel)
}

But it returns the error

tempLabel is not a member of view.

I think I need to use valueForKey function here but not sure how to implement it in Swift. Can you help me write that line of code?

Upvotes: 0

Views: 113

Answers (1)

drewag
drewag

Reputation: 94683

Instead of trying to dynamically create a name that references your labels, you can use an IBOutletCollection:

@IBOutlet var viewsToBringToFront: [UIView]!

You can connect all the views that you will want to bring to the front to that collection and simply loop through it to bring them to the front:

for view in viewsToBringToFront {
    view.superview?.bringSubviewToFront(view)
}

Upvotes: 2

Related Questions