Setting colors with an NSString

I wanted to color some letters in an NSAttributed string using a random list of colors that I generated. What I wanted to do was something like this:


NSString colorName = [NSString stringWithFormat:@"%@Color", colorList[i] ];
imageColor = [UIColor colorName];

But you can’t feed an NSString to the UIColor method. Use a selector to do it.
Like this:
 
NSString *colorname = [NSString stringWithFormat:@"%@Color", colorList[i] ];
SEL labelColor = NSSelectorFromString(colorname);
UIColor *imageColor = [Utilities uiColorFromColorName:colorname];
imageColor = [UIColor performSelector:labelColor];

I had to create pink separately since it is not in the Apple supplied color list. However, I don’t really like the other colors so I created a Utility method to create a UIColor from our RGB color values. It generates a UIColor that I can use for my attributed string.


UIColor *imageColor = [Utilities uiColorFromColorName:[lettersExploded[2] lowercaseString] ];


+ (UIColor *)uiColorFromColorName:(NSString *)colorName {

UIColor *imageColor = nil;

    if ( [colorName isEqualToString:@"black"] ) {
        imageColor = [UIColor colorWithRed:0.0f/255.0f green:0.0f/255.0f blue:0.0f/255.0f alpha:1];
    } else if ( [colorName isEqualToString:@"blue"] ) {
        imageColor = [UIColor colorWithRed:8.0f/255.0f green:41.0f/255.0f blue:247.0f/255.0f alpha:1];
    } else if ( [colorName isEqualToString:@"brown"] ) {
        imageColor = [UIColor colorWithRed:95.0f/255.0f green:47.0f/255.0f blue:0.0f/255.0f alpha:1];
    } else if ( [colorName isEqualToString:@"gray"] ) {
        imageColor = [UIColor colorWithRed:140.0f/255.0f green:140.0f/255.0f blue:140.0f/255.0f alpha:1];
    } else if ( [colorName isEqualToString:@"green"] ) {
        imageColor = [UIColor colorWithRed:51.0f/255.0f green:153.0f/255.0f blue:51.0f/255.0f alpha:1];
    } else if ( [colorName isEqualToString:@"orange"] ) {
        imageColor = [UIColor colorWithRed:255.0f/255.0f green:116.0f/255.0f blue:0.0f/255.0f alpha:1];
    } else if ( [colorName isEqualToString:@"pink"] ) {
        imageColor = [UIColor colorWithRed:255.0f/255.0f green:90.0f/255.0f blue:148.0f/255.0f alpha:1];
    } else if ( [colorName isEqualToString:@"purple"] ) {
        imageColor = [UIColor colorWithRed:140.0f/255.0f green:0.0f/255.0f blue:140.0f/255.0f alpha:1];
    } else if ( [colorName isEqualToString:@"red"] ) {
        imageColor = [UIColor colorWithRed:233.0f/255.0f green:17.0f/255.0f blue:0.0f/255.0f alpha:1];
    } else if ( [colorName isEqualToString:@"white"] ) {
        imageColor = [UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:1];
    } else if ( [colorName isEqualToString:@"yellow"] ) {
        imageColor = [UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:0.0f/255.0f alpha:1];
    }

  return imageColor;
}