How do I define constant values of UIColor?(如何定义 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
现在我可以在代码中执行以下操作:
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.
(顺便说一句,我开始更多地考虑 HSB 而不是 RGB,因为我更关注颜色.)
(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.
这篇关于如何定义 UIColor 的常量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何定义 UIColor 的常量值?
基础教程推荐
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01