如何定义UIColor的常量值? [英] 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.
推荐答案
我喜欢使用类别来扩展类,用这种方法的新方法。这里是我今天写的代码片段:
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
例如:
self.view.backgroundColor = highlight? [UIColor paleYellowColor] : [UIColor whitecolor];
和我自己定义的颜色合并在系统定义的颜色旁边。
and my own defined colors fit right in alongside the system-defined ones.
(顺便提一句,我开始更多地考虑HSB而不是RGB,因为我更注意颜色。)
(Incidentally, I am starting to think more in terms of HSB than RGB as I pay more attention to colors.)
UPDATE about precomputing the value:我的预感是,它不值得。但是如果你真的想要,你可以用静态变量记住值:
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.
这篇关于如何定义UIColor的常量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!