Reputation: 3780
I have defined the following constants, each of which represents a UIColor:
// Purple
#define PURPLE_COLOR_DARK [UIColor colorWithRed: 0.42 green: 0.25 blue: 0.60 alpha: 1.0]
#define PURPLE_COLOR_LIGHT [UIColor colorWithRed: 0.78 green: 0.47 blue: 0.72 alpha: 1.0]
// Blue
#define BLUE_COLOR_DARK [UIColor colorWithRed: 0.00 green: 0.46 blue: 0.70 alpha: 1.0]
#define BLUE_COLOR_LIGHT [UIColor colorWithRed: 0.00 green: 0.75 blue: 0.88 alpha: 1.0]
// Magenta
#define MAGENTA_COLOR_DARK [UIColor colorWithRed: 0.75 green: 0.00 blue: 0.28 alpha: 1.0]
#define MAGENTA_COLOR_LIGHT [UIColor colorWithRed: 1.00 green: 0.32 blue: 0.61 alpha: 1.0]
Question
How can I use an NSString
like @"purple"
, @"blue"
or @"magenta"
to get the related "X_COLOR_DARK" or "X_COLOR_LIGHT" constant? Is it even possible to do so directly?
Example
This is wrong, but should provide a clearer picture of what I'm asking. In this example, I have the string @"blue"
and want to derive the BLUE_COLOR_DARK
and BLUE_COLOR_LIGHT
color values.
NSString *color = @"blue";
UIColor *darkColor = (UIColor *)[[NSString stringWithFormat: @"%@_COLOR_DARK", color] uppercaseString];
// Debugging
NSLog(@"%@", darkColor); // BLUE_COLOR_DARK
NSLog(@"%hhd", [lightColor isKindOfClass: [UIColor class]]); // 0
NSLog(@"%hhd", [lightColor isKindOfClass: [NSString class]]); // 1
Follow-Up
Note that UIColor is not necessarily relevant to answering the question, though it does help for my situation. More specifically, I'm asking if a string matching a defined name (e.g. @"PURPLE_COLOR_DARK"
and #define PURPLE_COLOR_DARK
) can be interpreted as the defined name instead of using the defined name directly.
Upvotes: 3
Views: 1280
Reputation: 90117
Ditch the #defines. And use a UIColor
category and NSSelectorFromString
like outlined in this answer.
Or, create a NSDictionary
where the keys are the names of your colors and the objects are your colors. You can then get UIColor
by name.
E.g.:
NSDictionary *colors = @{ @"purple_dark" : PURPLE_COLOR_DARK,
@"purple_light" : PURPLE_COLOR_LIGHT };
NSString *colorName = @"purple";
NSString *lightColorName = [colorName stringByAppendingString:@"_light"];
NSString *darkColorName = [colorName stringByAppendingString:@"_dark"];
UIColor *lightColor = colors[lightColorName];
UIColor *darkColor = colors[darkColorName];
you can't use the #defined names directly because those names don't exist in the compiled code. During compilation the preprocessor will replace all occurrences of PURPLE_COLOR_DARK
with [UIColor ...]
Upvotes: 4
Reputation: 10959
You can create category of UIColor.
UIColor+CustomColors.h
+ (UIColor *)redFill;
UIColor+CustomColors.m
+ (UIColor *)redFill
{
return [UIColor colorWithRed:240.0 / 255.0 green:36.0 / 255.0 blue:0.0 / 255.0 alpha:1.0];
}
Now use this category in your class:
NSArray *color = @[[UIColor redFill], ...etc];
Upvotes: 3