How to convert a html hex string into UIColor with objective-c
Typically you should be using RGB (Red, Green, Blue) UIColor’s. However, every now and then you will need to create one from a HEX string. Probably from an API you have to deal with. None the less there is an ubundance of different methods you can use converting hex strings into UIColor objects. This is the solution I swear by and never had a problem with it thus far.
To get started, Create the two following files in your project.
UIColor+PXExtentions.h
#import <UIKit/UIKit.h>
@interface UIColor (UIColor_PXExtensions)
+ (UIColor*)pxColorWithHexValue:(NSString*)hexValue;
@end
UIColor+PXExtensions.m
#import "UIColor+PXExtensions.h"
@implementation UIColor (UIColor_PXExtensions)
+ (UIColor*)pxColorWithHexValue:(NSString*)hexValue
{
//Default
UIColor *defaultResult = [UIColor blackColor];
//Strip prefixed # hash
if ([hexValue hasPrefix:@"#"] && [hexValue length] > 1) {
hexValue = [hexValue substringFromIndex:1];
}
//Determine if 3 or 6 digits
NSUInteger componentLength = 0;
if ([hexValue length] == 3)
{
componentLength = 1;
}
else if ([hexValue length] == 6)
{
componentLength = 2;
}
else
{
return defaultResult;
}
BOOL isValid = YES;
CGFloat components[3];
//Seperate the R,G,B values
for (NSUInteger i = 0; i < 3; i++) {
NSString *component = [hexValue substringWithRange:NSMakeRange(componentLength * i, componentLength)];
if (componentLength == 1) {
component = [component stringByAppendingString:component];
}
NSScanner *scanner = [NSScanner scannerWithString:component];
unsigned int value;
isValid &= [scanner scanHexInt:&value];
components[i] = (CGFloat)value / 255.0f;
}
if (!isValid) {
return defaultResult;
}
return [UIColor colorWithRed:components[0]
green:components[1]
blue:components[2]
alpha:1.0];
}
@end
Usage
In your class file remember to import the category header file. In this case #import “UIColor+PXExtenions.h” Then use the following code to create your UIColor.
UIColor *mycolor = [UIColor pxColorWithHexValue:@"#BADA55"];
Hope that helps :))

Hello. I'm Byron Salau a Melbourne based developer who's an absolute objective-c and javascript junkie!