Objective-C试图为NSArray中的每个项目创建一个标签 - 不起作用

时间:2015-10-06 20:45:49

标签: ios objective-c

我有一个看起来像附加图像的数组

enter image description here

我想要做的是以下内容:

  • 为此NSArray运行foreach
  • 为阵列中的每个项目创建标签(因此3个分区标签,3个项目标签,3个WorkOrder标签和3个装配标签)

我有以下代码:

int counter = 0;
    for (id object in _theParamenterArray) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 30*counter + 10, 200, 200)];
        label.text = [object objectForKey:@"Assemble"];
        [label setFont:[UIFont boldSystemFontOfSize:16]];
        [self.view addSubview:label];

        UILabel *labelTwo = [[UILabel alloc]initWithFrame:CGRectMake(110, 30*counter + 10, 200, 200)];
        label.text = [object objectForKey:@"Division"];
        [label setFont:[UIFont boldSystemFontOfSize:16]];
        [self.view addSubview:labelTwo];

        UILabel *labelThree = [[UILabel alloc]initWithFrame:CGRectMake(210, 30*counter + 10, 200, 200)];
        label.text = [object objectForKey:@"Project"];
        [label setFont:[UIFont boldSystemFontOfSize:16]];
        [self.view addSubview:labelThree];

        UILabel *labelFour = [[UILabel alloc]initWithFrame:CGRectMake(310, 30*counter + 10, 200, 200)];
        label.text = [object objectForKey:@"WorkOrder"];
        [label setFont:[UIFont boldSystemFontOfSize:16]];
        [self.view addSubview:labelFour];
        counter++;
    }

我对此代码的问题是它总共只创建了4个标签,而数据是数组中的最后一项,因此它会覆盖这些值。我的问题如何解决这个问题?请帮助!

2 个答案:

答案 0 :(得分:4)

你只为“label”变量设置文本:)这是一个复制/粘贴bug :) 重命名标签 - > labelTwo,labelThree,labelFour for lines:

label.text = [object objectForKey:@"WorkOrder"];
[label setFont:[UIFont boldSystemFontOfSize:16]];

答案 1 :(得分:1)

看起来您的问题是将文字和字体分配到label 4次,请尝试以下操作:

int counter = 0;
    for (id object in _theParamenterArray) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 30*counter + 10, 200, 200)];
        label.text = [object objectForKey:@"Assemble"];
        [label setFont:[UIFont boldSystemFontOfSize:16]];
        [self.view addSubview:label];

        UILabel *labelTwo = [[UILabel alloc]initWithFrame:CGRectMake(110, 30*counter + 10, 200, 200)];
        labelTwo.text = [object objectForKey:@"Division"];
        [labelTwo setFont:[UIFont boldSystemFontOfSize:16]];
        [self.view addSubview:labelTwo];

        UILabel *labelThree = [[UILabel alloc]initWithFrame:CGRectMake(210, 30*counter + 10, 200, 200)];
        labelThree.text = [object objectForKey:@"Project"];
        [labelThree setFont:[UIFont boldSystemFontOfSize:16]];
        [self.view addSubview:labelThree];

        UILabel *labelFour = [[UILabel alloc]initWithFrame:CGRectMake(310, 30*counter + 10, 200, 200)];
        labelFour.text = [object objectForKey:@"WorkOrder"];
        [labelFour setFont:[UIFont boldSystemFontOfSize:16]];
        [self.view addSubview:labelFour];
        counter++;
    }

查看数组的代码会有所帮助。