How do I define constant values of UIColor?

To expand on jasoncrawford's answer (I'd put this in as a comment, but you can't format code in the comments) if you want to precompute the values (or do it only once).

+ (UIColor *)paleYellowColor
{
    static UIColor* paleYellow = nil;
    if (paleYellow == nil)
    {
        paleYellow = [UIColor colorWithHueDegrees:60 saturation:0.2 brightness:1.0];
    }
    return paleYellow;
}

The reason your original idea doesn't work is because the compiler can only use initialisers outside of functions, not normal code. You could have achieved something like what you wanted with the initialize methosd e.g.

static UIColor* colorNavBar = nil;

+(void) initialize
{
    if (colorNavBar != nil)
    {
        colorNavBar = ....
    }
}

NB the const qualifier on your original definition is redundant since UIColor is immutable anyway.


I usually make a category of UIColor for each project:

@interface UIColor (ProjectName)

+(UIColor *) colorForSomeTable;
+(UIColor *) colorForSomeControl;
+(UIColor *) colorForSomeText;

@end

With the constants in the implementation:

@implementation UIColor (ProjectName)

+(UIColor *) colorForSomeTable { return [UIColor colorWithRed:...]; }

@end

I also do the same for UIFont and UIImage as needed.


I like to use categories to extend classes with new methods for this sort of thing. Here's an excerpt of code I just wrote today:

@implementation UIColor (Extensions)

+ (UIColor *)colorWithHueDegrees:(CGFloat)hue saturation:(CGFloat)saturation brightness:(CGFloat)brightness {
    return [UIColor colorWithHue:(hue/360) saturation:saturation brightness:brightness alpha:1.0];
}

+ (UIColor *)aquaColor {
    return [UIColor colorWithHueDegrees:210 saturation:1.0 brightness:1.0];
}

+ (UIColor *)paleYellowColor {
    return [UIColor colorWithHueDegrees:60 saturation:0.2 brightness:1.0];
}

@end

Now in code I can do things like:

self.view.backgroundColor = highlight? [UIColor paleYellowColor] : [UIColor whitecolor];

and my own defined colors fit right in alongside the system-defined ones.

(Incidentally, I am starting to think more in terms of HSB than RGB as I pay more attention to colors.)

UPDATE regarding precomputing the value: My hunch is that it's not worth it. But if you really wanted, you could memoize the values with static variables:

+ (UIColor *)paleYellowColor {
    static UIColor *color = nil;
    if (!color) color = [UIColor colorWithHueDegrees:60 saturation:0.2 brightness:1.0];
    return color;
}

You could make a macro do do the memoizing, too.