Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

objective c - How do I define constant values of UIColor?

I want to do something like this, but I cannot get a cooperative syntax.

static const UIColor *colorNavbar = [UIColor colorWithRed: 197.0/255.0 green: 169.0/255.0 blue: 140.0/255.0 alpha: 1.0];

I suppose that I could define macros, but they are ugly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...