Using a Hex (html) color code as a UIColor

hash keyWe had a requirement to read from a plist a hex color code eg. #168240 and translate that to update a navigation controller’s navigation bar background color.

Below are two ways that were presented.


First (not the best) was this method using a macro, but this wasn’t obvious to us how to use it with an NSString value for the color code (we couldn’t hard code it).

//RGB color macro
#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]

and then use in code like this:

tintColor = UIColorFromRGB(0x168240);


Second (preferred) was to create a method that returns a UIColor with parameters allowing for an NSString to be passed.

-(UIColor *) colorForHex:(NSString *)hexColor {
hexColor = [[hexColor stringByTrimmingCharactersInSet:
                 ] uppercaseString]; 
    // String should be 6 or 7 characters if it includes ‘#’ 
    if ([hexColor length] < 6)
return [UIColorblackColor]; 
    // strip # if it appears 
    if ([hexColor hasPrefix:@"#"])
hexColor = [hexColor substringFromIndex:1]; 
    // if the value isn’t 6 characters at this point return
    // the color black
    if ([hexColor length] != 6)
return [UIColorblackColor]; 
    // Separate into r, g, b substrings 
    NSRange range; 
    range.location = 0; 
    range.length = 2;
    NSString *rString = [hexColor substringWithRange:range]; 
    range.location = 2; 
    NSString *gString = [hexColor substringWithRange:range]; 
    range.location = 4; 
    NSString *bString = [hexColor substringWithRange:range]; 
    // Scan values 
    unsignedint r, g, b; 
    [[NSScannerscannerWithString:rString] scanHexInt:&r]; 
    [[NSScannerscannerWithString:gString] scanHexInt:&g]; 
    [[NSScannerscannerWithString:bString] scanHexInt:&b]; 
    return [UIColorcolorWithRed:((float) r / 255.0f) 
                           green:((float) g / 255.0f) 
                            blue:((float) b / 255.0f) 

And access it like this:

tintColor = [self colorForHex:@"#168240"];

Leave a Reply

Your email address will not be published. Required fields are marked *