Thorsten
Thorsten

Reputation: 13181

Looping over similarly named UI elements - maybe by getting a variable from its name?

I've added a number of labels to a view using Interface Builder. I've also got an array of values I want to display.

Is there a better way to set the labels than using this code:

lblTotal1.text = [NSString stringWithFormat: @"%i Seconds", (int) round(fTimeTotal[1])];
lblTotal2.text = [NSString stringWithFormat: @"%i Seconds", (int) round(fTimeTotal[2])];
lblTotal3.text = [NSString stringWithFormat: @"%i Seconds", (int) round(fTimeTotal[3])];
lblTotal4.text = [NSString stringWithFormat: @"%i Seconds", (int) round(fTimeTotal[4])];

What I'd like to do is something like this:

for (int i = 1; i<5; i++) {
    lblTotal[i].text = [NSString stringWithFormat: @"%i Seconds", (int) round(fTimeTotal[i])];
}

But I have to be able to get a variable from it's name. How can I do this?

Upvotes: 0

Views: 632

Answers (3)

Rob Napier
Rob Napier

Reputation: 299355

You can hook our IBOutlets together in an IBOutletCollection in IB (select a bunch and drag them to the source code together; it should offer to make a collection). While an IBOutletCollection is technically an ordered list (array), it is in fact randomly ordered.

Once you've hooked all your IBOutlets together into an IBOutletCollection, you'll still need to know which is which. You do this with tag, which is one of the fields you can set in IB. Once you've tagged them all, your code will be:

for (UILabel *label in self.labelCollection) {
  int value = (int)roundf(fTimeTotal[label.tag]);
  label.text = [NSString stringWithFormat:@"%i Seconds", value];
}

Upvotes: 6

Monolo
Monolo

Reputation: 18253

If your variables like lblTotal1 are properties, you can use key-value coding (KVC) to obtain them:

NSUInteger lblIndex = 1;
NSString *lblName = @[NSString stringWithFormat: @"lblTotal%d", lblIndex];

id label = [self valueForKey: lblName];

Depending on whether you are targeting iOS or OS X, the id in the last line could be any specific class for your label, of course.

Upvotes: 2

Nebary
Nebary

Reputation: 499

You can use self.view.subviews array to go through all subviews and check if it is UILabel, do your things.

Upvotes: 0

Related Questions