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

前端 未结 3 518
野趣味
野趣味 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];
    }
    
    0 讨论(0)
  • 2021-01-17 03:43

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

    0 讨论(0)
  • 2021-01-17 03:47

    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.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题