Using Categories with UIColor | Code | My Website

Using Categories with UIColor

One way of globally caching frequently used UIColor values can be by using a category on UIColor.

This allows code such as..
aLabelView.textColor = [UIColor lightBeigeColor];

This is especially useful when optimising cellForRowAtIndexPath in a UITableView where all the subviews of the UITableViewCell being returned are being created programmatically for speed.

Example header file...
//  Add a category on to UIColor to add some of our own regularly used colours
#import <UIKit/UIKit.h>
@interface UIColor (UIColor_SDJColor)
+ (UIColor *) lightBeigeColor;
+ (UIColor *) darkBeigeColor;
@end

Example source file...
#import "UIColor+SDJColor.h"
@implementation UIColor (UIColor_SDJColor)
+ (UIColor *) lightBeigeColor;
{
static UIColor *lightBeige = nil;
// If we haven't already initialised the colour, then do it now
if (!lightBeige) {
lightBeige = [UIColor colorWithRed: 0.925f
green: 0.902f
blue: 0.835f
alpha: 1.000f];
[lightBeige retain];
}
return lightBeige;
}

+ (UIColor *) darkBeigeColor;
{
static UIColor *darkBeige = nil;
// If we haven't already initialised the colour, then do it now
if (!darkBeige) {
darkBeige = [UIColor colorWithRed: 0.875f
green: 0.839f
blue: 0.723f
alpha: 1.000f];
[darkBeige retain];
}
return darkBeige;
}
@end

This method can also be used to cache frequently used objects with other classes such as UIFont and UIImage where otherwise repeated calls could be expensive in terms of CPU time.
blog comments powered by Disqus