Search code examples
iosuicolor

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!


Solution

  • 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++;
    }