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

前端 未结 3 546
野趣味
野趣味 2021-01-17 02:58

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 u

3条回答
  •  情深已故
    2021-01-17 03:30

    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];
    }
    

提交回复
热议问题