LE SANG
LE SANG

Reputation: 11005

How to set color by pointer to color name?

Normal, I often setBackgound color by: aView.backgroundColor = [UIColor redColor];

Now I keep all color name in an NSArray:

colorsArray = [[NSMutableArray alloc] initWithObjects:
               @"blackColor",
               @"darkGrayColor",
               @"lightGrayColor",
               @"whiteColor",
               @"grayColor",
               @"redColor",
               @"greenColor",
               @"blueColor",
               @"cyanColor",
               @"yellowColor",
               @"magentaColor",
               @"orangeColor",
               @"purpleColor",
               @"brownColor",
               nil];

And I want to set background by a NSString pointer like that

NSInteger i = 0;
for (aView in viewArray) {
   NSString *colorName = [colorsArray objectAtIndex:i];
   aView.backgroundColor = color with colorName;//Can't find a method to set
   i++;
}

I check UIColor class and can't find any method to set color with pointer to colorName. Please help! Any another way? Thanks!

Upvotes: 0

Views: 622

Answers (2)

trojanfoe
trojanfoe

Reputation: 122391

aView.backgroundColor = [UIColor performSelector:NSSelectorFromString(colorName)];

Upvotes: 2

user529758
user529758

Reputation:

A little bit of reflection and the medicine goes down...

NSInteger i = 0;
for (aView in viewArray) {
    NSString *colorName = [colorsArray objectAtIndex:i];
    aView.backgroundColor = [[UIColor class] performSelector:NSSelectorFromString(colorName)];
   i++;
}

Upvotes: 5

Related Questions