Objective C defining UIColor constants Objective C defining UIColor constants objective-c objective-c

Objective C defining UIColor constants


A UIColor is not mutable. I usually do this with colors, fonts and images. You could easily modify it to use singletons or have a static initializer.

@interface UIColor (MyProject)+(UIColor *) colorForSomePurpose;@end@implementation UIColor (MyProject)+(UIColor *) colorForSomePurpose { return [UIColor colorWithRed:0.6 green:0.8 blue:1.0 alpha:1.0]; }@end


For simplicity I did this:

/* Constants.h */#define myColor [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0]

Don't forget to leave out the ';' so you can use it as a normal expression.

I'm not sure if there's anything technically wrong with this approach, but it works fine, and avoids the compile-time constant initializer error - this code is effectively stuck in place anywhere you put 'myColor', so it doesn't ever get compiled until you actually use it.


Another option

in your .h you can do

extern UIColor *  const COLOR_LIGHT_BLUE;

in your .mm you can do

UIColor* const COLOR_LIGHT_BLUE = [[UIColor alloc] initWithRed:21.0f/255 green:180.0f/255  blue:1 alpha:1];//;#15B4FF