Working with hex colours

We’ve all been there when a designer has passed over the colours to be used in our application only to find that they have given us the value in hex. This means we now have to scramble to open our HexToRGB application or include some convoluted category on UIColor that adds a bunch of methods doing a load of calculations. The majority of the time adding these helper methods to UIColor is likely us just being heavy handed. The task can have a much simpler resolution.

##Solution

So our designer has just finished perfectly tweaking his palette and has given us #66CDAA for that “Medium Aqua Marine” colour we so badly needed. As our application will have a selective palette of colours I would still take the opportunity to create a category with factory methods for creating the different palette colours. Our “Medium Aqua Marine” might look something like this

@interface UIColor (ApplicationPalette)

+ (UIColor *)ps_mediumBackgroundColor;

@end

@implementation UIColor (ApplicationPalette)

+ (UIColor *)ps_mediumBackgroundColor;
{
  return [self colorWithRed:0x66/255 green:0xCD/255 blue:0xAA/255 alpha:1.f];
}

@end

The beauty of this snippet can easily be overlooked on first glance. Take note of the fact that I have just preceded the hex value with 0x so that C knows that we are talking in terms of hex. Also note that I tried to avoid using the colour name in the category, this means that I can change the palette colour to be a medium red and not have to find everywhere that I previously used the category that referenced the colour green in the name.

##Conclusion

This may seem like a trivial snippet but you’ll appreciate the technique when you have the designer sat over your shoulder rapidly barking out hex values as they try to get the maximum effect from their design when deployed to the actual hardware. Also note the usefulness of being DRY and writing this category so that we don’t need to search every in our code to make small tweaks to out palette.