UIColorFromRGB

7 August 2014

I can’t remember where I originally came across it, but this is a handy Objective-C macro I’m using in Daily Offers for constructing a UIColor instance from a CSS hex colour:

#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

I popped it in DailyOffers-Prefix.pch so it’s available anywhere.

Here it is being used in a UIColor category I created that allows me to use semantic colour names throughout the Daily Offers code base:

//
//  UIColor+DailyOffersAdditions.m
//  Daily Offers
//
//  Created by John Topley on 02/08/2012.
//  Copyright (c) 2012 John Topley. All rights reserved.
//

#import "UIColor+DailyOffersAdditions.h"

@implementation UIColor (DailyOffersAdditions)

+ (UIColor *)dailyOffersMessageBarErrorColour
{
    return UIColorFromRGB(0xD96713);
}

+ (UIColor *)dailyOffersMessageBarInfoColour
{
    return UIColorFromRGB(0x0C877A);
}

+ (UIColor *)dailyOffersMessageBarSuccessColour
{
    return UIColorFromRGB(0x26B310);
}

+ (UIColor *)dailyOffersSectionIndexColour
{
    return UIColorFromRGB(0xD3131F);
}

+ (UIColor *)dailyOffersSeparatorColour
{
    return UIColorFromRGB(0xC8C7CC);
}

+ (UIColor *)dailyOffersStatusBarColour
{
    return UIColorFromRGB(0xD3131F);
}

@end