iOS UIColor got you down? Get hexed with UIColor

Jonas Schnelli has a good UIColor implementation for Objective-C which will allow you to use Hex colors for UIColor, including alpha values… all by using an NSString implementation. Short, sweet, and it works like a charm. Check the link to the github location.

If you’re interested in seeing what’s under the hood at the moment in the implementation (.m) file, here you go.

#import "UIColor+i7HexColor.h"

@implementation UIColor (i7HexColor)

+ (UIColor *)colorWithHexString:(NSString *)hexString {

	/* convert the string into a int */
	unsigned int colorValueR,colorValueG,colorValueB,colorValueA;
	NSString *hexStringCleared = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
	if(hexStringCleared.length == 3) {
		/* short color form */
		/* im lazy, maybe you have a better idea to convert from #fff to #ffffff */
		hexStringCleared = [NSString stringWithFormat:@"%@%@%@%@%@%@", [hexStringCleared substringWithRange:NSMakeRange(0, 1)],[hexStringCleared substringWithRange:NSMakeRange(0, 1)],
												[hexStringCleared substringWithRange:NSMakeRange(1, 1)],[hexStringCleared substringWithRange:NSMakeRange(1, 1)],
												[hexStringCleared substringWithRange:NSMakeRange(2, 1)],[hexStringCleared substringWithRange:NSMakeRange(2, 1)]];
	if(hexStringCleared.length == 6) {
		hexStringCleared = [hexStringCleared stringByAppendingString:@"ff"];

	/* im in hurry */
	NSString *red = [hexStringCleared substringWithRange:NSMakeRange(0, 2)];
	NSString *green = [hexStringCleared substringWithRange:NSMakeRange(2, 2)];
	NSString *blue = [hexStringCleared substringWithRange:NSMakeRange(4, 2)];
	NSString *alpha = [hexStringCleared substringWithRange:NSMakeRange(6, 2)];

	[[NSScanner scannerWithString:red] scanHexInt:&colorValueR];
	[[NSScanner scannerWithString:green] scanHexInt:&colorValueG];
	[[NSScanner scannerWithString:blue] scanHexInt:&colorValueB];
	[[NSScanner scannerWithString:alpha] scanHexInt:&colorValueA];

	return [UIColor colorWithRed:((colorValueR)&0xFF)/255.0

Related Posts Plugin for WordPress, Blogger...

One thought on “iOS UIColor got you down? Get hexed with UIColor

  1. Pingback: Tweets that mention iOS UIColor got you down? Get hexed with UIColor --

Leave a Reply

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

seven − 5 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>