Reputation: 115
I am trying to streamline a little project that I am working on where I have eight UILabels, and every so often I have the background color of these labels change to a different color based on data stored in an array.
Currently my code runs a for loop from 0 to 7 (to account for the eight UILabels). Within the for loop, it will check what number the for loop is upto and amend the corresponding UILabel with the new background color, like this:
for (int y = 0; y < 8; y++) {
SEL mySelect = NSSelectorFromString([backgroundColorData objectAtIndex:y]);
UIColor* myUILabelColor = nil;
if ([UIColor respondsToSelector: mySelect]){
myUILabelColor = [UIColor performSelector:mySelect];
}
switch (y) {
Label0.backgroundColor = myUILabelColor;
break;
case 1:
Label1.backgroundColor = myUILabelColor;
break;
case 2:
Label2.backgroundColor = myUILabelColor;
break;
case 3:
Label3.backgroundColor = myUILabelColor;
break;
case 4:
Label4.backgroundColor = myUILabelColor;
break;
case 5:
Label5.backgroundColor = myUILabelColor;
break;
case 6:
Label6.backgroundColor = myUILabelColor;
break;
case 7:
Label7.backgroundColor = myUILabelColor;
break;
}
I would like to be able to make the code scaled down by placing these 8 UILabels into an array and perhaps making the code read as follows:
for (int y = 0; y < 8; y++) {
SEL mySelect = NSSelectorFromString([backgroundColorData objectAtIndex:y]);
UIColor* myUILabelColor = nil;
if ([UIColor respondsToSelector: mySelect]){
myUILabelColor = [UIColor performSelector:mySelect];
}
// This piece of code would deal with modifying the backgroundColor of UILabel(y) within my array of UILabels.
}
Or now that I think about it, perhaps I could do it all in one big hit whereby I don't need to run through a for loop eight times, but I could just directly send the contents of my backgroundcolordata array into my UILabel array?
Any help or tips here would be very much appreciated.
Upvotes: 1
Views: 4878
Reputation: 15442
You can get the label by name, which can be a useful technique sometimes:
NSString *name = [NSString stringWithFormat:@"Label%d", y];
UILabel *label = [self valueForKey:name];
backgroundColor = myUILabelColor = name;
P.S. Instances should really start with a lower case letter. i.e. 'label1', not 'Label1'.
Upvotes: 3
Reputation: 299275
First, I would just store actual UIColor
objects in backgroundColorData
rather than names of colors. Then store the UILabel
objects in an array. Then the entire code looks like this:
NSUInteger count = [self.labels count];
for (NSUInteger index = 0; index < count; ++index) {
UIColor *color = [self.backgroundColors objectAtIndex:index];
[[self.labels objectAtIndex:index] setBackgroundColor:color];
}
Upvotes: 3