How do I define constant values of UIColor?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)