Sam B
Sam B

Reputation: 27618

UILabel multi-set values

I know this is going to sound like a trivial question but I have defined 50 labels in my *.h file

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

In my *.c file I want to set the value for each of those labels but I don't want to do it manually or write them out over and over again.

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

Upvotes: 0

Views: 247

Answers (3)

Lloyd Sargent
Lloyd Sargent

Reputation: 614

Well one way that comes to mind (not the cleanest but A way) is to do the following:

UILabel *tempLabels[50];

The problem you run into then is you can't use IB to connect them. Instead what you do is use the tag property in each of them (this means you need to set the tag for all 50 UILabels). To properly connect them you run this in viewDidLoad:

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

Bingo! Now anywhere in your code if you need to change the labels you can do the following:

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

It's kind of tedious setting the tags, but once you are done, you are done.

BTW, unlike the other solutions, you can use IB to create your labels.

Upvotes: 2

holex
holex

Reputation: 24031

this would be a good start for you, I guess.

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

Upvotes: 1

user387184
user387184

Reputation: 11053

You can add the UILabels programmatically and hence have access to them - so you can set their text value as well.

You can add a UILabel like this:

    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

If you need access to the labels later as well, just add them to an NSArray that you keep.

Upvotes: 0

Related Questions