我应该在哪里存储30+ UIColors以便快速参考?

我想要有30多个常用的UIColors,所以我可以在我的应用程序中轻松访问它们。 我想能够做到这样的事情:

[self setBackgroundColor:[UIColor skyColor]]; [self setBackgroundColor:[UIColor dirtColor]]; [self setBackgroundColor:[UIColor yankeesColor]]; 

我怎样才能做到这一点?

谢谢!!

UIColor定义一个类别:

在UIColor + MyColors.h中:

 @interface UIColor (MyColors) + (UIColor *)skyColor; + (UIColor *)dirtColor; // and the rest of them @end 

在UIColor + MyColors.m中:

 @implementation UIColor (MyColors) + (UIColor *)skyColor { static UIColor color = nil; if (!color) { // replace r, g, and b with the proper values color = [UIColor colorWithRed:r green:g blue:b alpha:1]; } return color; } + (UIColor *)dirtColor { static UIColor color = nil; if (!color) { // replace r, g, and b with the proper values color = [UIColor colorWithRed:r green:g blue:b alpha:1]; } return color; } // and the rest @end 

编辑:

正如马丁R指出的,一个更现代的方法来初始化静态colorvariables将是:

 + (UIColor *)skyColor { static UIColor color = nil; static dispatch_once_t predicate = 0; dispatch_once(&predicate, ^{ // replace r, g, and b with the proper values color = [UIColor colorWithRed:r green:g blue:b alpha:1]; }); return color; } 

在这种情况下,这实际上可能是矫枉过正的,因为如果两个线程在使用原始代码的同时初始化nil静态variables时没有不良副作用。 但是使用dispatch_once是一个更好的习惯。

你可以添加这样的行:

 #define kFirstColor [UIColor whiteColor] #define kSecondColor [UIColor colorWithRed:100.0/255 green:100.0/255 blue:100.0/255 alpha:1.0] 

在一个类的开始处或者将Color.h头添加到项目中,并在需要时导入它。

 #import "Color.h" 

那么你可以用这种方式使用你的自定义颜色:

 self.view.backgroundColor = kSecondColor;