2 notes &
Managing Color With UIColor Categories
I find it nice to have all the colors for my application contained in one file. This makes it easy to tweak the colors of the app without hunting. How I do this, is to create a Colors.h file and import it in the prefix.pch file. The prefix.pch file is located in “other sources” by default in a new xcode project. The file should look something like this…
#ifdef __OBJC__ #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "Colors.h" #endif
This will include the Colors.h file into every file in your project. With this you will be able to access your colors from everywhere without having to import.
In the Colors.h file I have my UIColor Extra category. This category has some convenience methods for creating colors. There is a method for creating a random UIColor and a method for creating a UIColor from a hex value. I prefer using hex values over RGB since they feel more comfortable to me.
@interface UIColor (Extra)
+ (UIColor *) randomColor;
+ (UIColor *) colorWithHex:(uint) hex;
@end
@implementation UIColor (Extra)
+ (UIColor *) randomColor
{
CGFloat red = (CGFloat)random()/(CGFloat)RAND_MAX;
CGFloat blue = (CGFloat)random()/(CGFloat)RAND_MAX;
CGFloat green = (CGFloat)random()/(CGFloat)RAND_MAX;
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}
+ (UIColor *) colorWithHex:(uint) hex
{
int red, green, blue, alpha;
blue = hex & 0x000000FF;
green = ((hex & 0x0000FF00) >> 8);
red = ((hex & 0x00FF0000) >> 16);
alpha = ((hex & 0xFF000000) >> 24);
return [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha/255.f];
}
@end
Here is two examples to show the usage of these two new methods.
// Set the background color of a UIView to black. myview.BackgroundColor = [UIColor colorWithHex:0xFF000000]; //Set the background color of a UIView to a random color. myview.BackgroundColor = [UIColor randomColor];
Now, all that needs to be done is adding our custom colors as another category.
@interface UIColor (Custom)
+ (UIColor *) myCustomColor;
@end
@implementation UIColor (Custom)
+ (UIColor *) myCustomColor;
{
return [UIColor colorWithHex:0xFFFFFFFF];
}
@end
You can create as many convenience methods in this file as you like. They will all be accessible from everywhere in your application.



