The more I develop iOS mobile apps, the more I find myself customizing existing classes using Categories. Most recently, I’ve found myself in need of using a set of custom colors, and making a category on top of the UIColor class allows a great way to add custom colors for use throughout an app.
If you’re new to Categories, making one is super easy, and only takes a few quick steps.
Step 1: Create New Category File
First, create a new file based on the Cocoa Touch “Objective-C category” template:
Next, name your Category and choose which class it’s a category on. For this example, I named it “ColorExtensions”, which is a category on UIColor:
Step 2: Add Custom Methods
Once your category file is created, you can add your custom method declarations in the “.h” file, and flesh them out in the implementation in the “.m” file:
@interface UIColor (ColorExtensions)
+ (UIColor *) darkSlateColor;
+ (UIColor *) mintGreenColor;
@implementation UIColor (ColorExtensions)
+ (UIColor *) darkSlateColor
return [UIColor colorWithRed:34.0/255.0 green:39.0/255.0 blue:44.0/255.0 alpha:1.0];
+ (UIColor *) mintGreenColor
return [UIColor colorWithRed:75.0/255.0 green:185.0/255.0 blue:159.0/255.0 alpha:1.0];
Step 3: Use Your Custom Colors
To use one of the custom colors in your code, just import the category class and reference the UIColor method of the color you want to use:
- (void) viewDidLoad
self.view.backgroundColor = [UIColor darkSlateColor];
While Categories are nothing new for iOS development, they do hold enormous power to help make your development process easier and more streamlined. In the case of extending UIColor, I find it to be a life-saver, enabling me to reference colors by name rather than having to type in the same RGB values multiple times in dozens of different places. Plus, if and when a color value needs to be updated, you simply change it in the Category file and boom – all references to that color are automatically updated as well.
Until next time, happy coding!