Reputation: 35993
I have to change the background color of several views that have the same base name like color1, color2, color3, etc., to the same color
I could simply do something like
color1.backgroundColor = theColor;
color2.backgroundColor = theColor;
color3.backgroundColor = theColor;
color4.backgroundColor = theColor;
...
but I would rather do that in a more elegant way using a loop, something like
NSString *baseName = @"color";
for (int i=1; i<numberOfViews; i++) {
NSString *tempName = [NSString stringWithFormat:@"%@%d", baseName, i];
// now that I have the correct name of the view as a string on tempName
// how do I reference the view which name is on tempName, so I can change its color?
}
thanks.
Upvotes: 1
Views: 157
Reputation: 84338
The approach you are trying to take would work in a language like JavaScript that allows you to take a string of text and send it to the interpreter at runtime. As a compiled language, Objective-C doesn't allow this.
Instead, you need to put your views in an array first, then you can iterate through them. The easiest way would be:
NSArray *views = [NSArray arrayWithObjects:color1, color2, color3, color4, nil];
for (UIView *v in views) {
v.backgroundColor = theColor;
}
Upvotes: 4