I want to have 30+ constant UIColors so I can easily access them in my app. I\'d like to be able to do something like this:
[self setBackgroundColor:[UICol
Define a category for UIColor
:
In UIColor+MyColors.h:
@interface UIColor (MyColors)
+ (UIColor *)skyColor;
+ (UIColor *)dirtColor;
// and the rest of them
@end
In 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
Edit:
As Martin R points out, a more modern approach to initializing the static color
variable would be:
+ (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;
}
This may actually be overkill in this case since there is no bad side-effect if two threads happen to initialize the nil
static variable at the same time using the original code. But it is a better habit to use dispatch_once
.
You can add lines like this:
#define kFirstColor [UIColor whiteColor]
#define kSecondColor [UIColor colorWithRed:100.0/255 green:100.0/255 blue:100.0/255 alpha:1.0]
At the beginning of a class or add a Color.h header to your project and import it when needed.
#import "Color.h"
Then you can use your custom colors this way:
self.view.backgroundColor = kSecondColor;