0

我知道这听起来像是一个微不足道的问题,但我在 *.h 文件中定义了 50 个标签

UILabel *tempLabel1;
UILabel *tempLabel2;
UILabel *tempLabel3;
...
UILabel *tempLabel50;

在我的 *.c 文件中,我想为每个标签设置值,但我不想手动执行或一遍又一遍地写出来。

//Instead of doing this
tempLabel1.text = @"1";
tempLabel2.text = @"2";
...
tempLabel50.text = @"50";   


//I would like to do something like this
//I know this isn't correct syntax but want to know if something like
//this can be done?
for (int i = 0; i < 50; i++) 
{
    tempLabel[i].text = @"%d", i+1;
}
4

3 回答 3

2

想到的一种方法(不是最干净的方法,而是一种方法)是执行以下操作:

UILabel *tempLabels[50];

您遇到的问题是您无法使用 IB 连接它们。相反,您所做的是在每个标签中使用标签属性(这意味着您需要为所有 50 个 UILabel 设置标签)。要正确连接它们,请在 viewDidLoad 中运行:

for (index = 1; index < 50; ++index)
{
    tempLabels[index] = (UILabel *) [self.view viewWithTag: index];
}

答对了!现在,如果您需要更改代码中的任何位置,您可以执行以下操作:

for (index = 1; index < 50; ++index)
{
    tempLabels[index].text = [NSString stringWithFormat: @"Number %d", index];
}

设置标签有点乏味,但一旦你完成了,你就完成了。

顺便说一句,与其他解决方案不同,您可以使用 IB 来创建标签。

于 2012-08-07T15:00:04.613 回答
1

我想这对你来说是一个好的开始。

NSMutableArray *_labels = [NSMutableArray array];

for (int i = 1; i < 50; i++) {
    UILabel *_newLabel = [[UILabel alloc] init]; // please, make the init method as you wish
    // ... any customization of the UILabel
    [_newLabel setText:[NSString stringWithFormat:@"%d", i]];
    [_newLabel setTag:i];
    [_labels addObject:_labels];
    [self.view addSubview:_newLabel];
}

// ... and then you can do the following

for (int i = 0; i < _labels.count; i++) {
    [((UILabel *)[_labels objectAtIndex:i]) setText:[NSString stringWithFormat:@"%d", i]];
}
于 2012-08-07T14:51:50.980 回答
0

您可以以编程方式添加 UILabel 并因此可以访问它们 - 因此您也可以设置它们的文本值。

您可以像这样添加 UILabel:

    UILabel *theLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)]; //need to calculate the x,y coordinates in dependency of i
    theLabel.text =  [NSString stringWithFormat:@"%i",i];
    [self.view addSubview:theLabel]; // add it to your view
    myLabel.backgroundColor = [UIColor clearColor]; // change the color

如果您以后还需要访问标签,只需将它们添加到您保留的 NSArray 中。

于 2012-08-07T14:48:19.147 回答