Looping over similar UI elements - perhaps getting a variable from its name?

I have added some labels to the view using the Interface Builder. I also have an array of values โ€‹โ€‹that I want to display.

Is there a better way to install shortcuts 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 would 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 should be able to get a variable from that name. How can i do this?


source to share

3 answers

You can connect our IBOutlets together in an IBOutletCollection in IB (select a bundle and drag them into the source code together, it should prompt to create a collection). Although IBOutletCollection is technically an ordered list (array), it is actually ordered in order.

Once you wire all your IBOutlets together to the IBOutletCollection, you still need to know what exactly. You do this with tag

, which is one of the fields that you can set in IB. After you've tagged them all, your code looks like this:

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




If your type variables lblTotal1

are properties, you can use keyed encoding (KVC) to get them:

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

id label = [self valueForKey: lblName];


Depending on whether you are configured for iOS or OS X, id

the last line could be any specific class for your label, of course.



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



All Articles