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?
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: