Custom UIColor Extensions for iOS

Custom UIColor Extensions for iOS

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:

Xcode New File Template Selection - Objective-C Category

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:

Xcode New Category File Options

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:

//
// UIColor+ColorExtensions.h
//
 
#import
 
@interface UIColor (ColorExtensions)
 
+ (UIColor *) darkSlateColor;
+ (UIColor *) mintGreenColor;
 
@end

//
// UIColor+ColorExtensions.m
//
 
#import "UIColor+ColorExtensions.h"
 
@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];
}
 
@end

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:

//
// MySampleViewController.m
//
 
#import "UIColor+ColorExtensions.h"
 
- (void) viewDidLoad
{
  [super viewDidLoad];
  self.view.backgroundColor = [UIColor darkSlateColor];
}

Wrapping Up

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!

There are no comments yet, add one below.

Leave a Comment