HEX value in Objective-C

Jakub picture Jakub · Apr 24, 2012 · Viewed 7.7k times · Source

I want to create UIColor from HEX value. But my Color is a NSString. So i implement this solution: How can I create a UIColor from a hex string?

code:

#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 i have (simplify):

NSString *myString = [[NSString alloc] initWithString:@"0xFFFFFF"];

So when i want to call macro:

UIColor *myColor = UIColorFromRGB(myString);

I'm getting an error: invalid operands to binary expression ('NSString *' and 'int')

So i know i have to pass int, but how to convert NSString to int in this case? Of course [myString intValue]; does not work here.

Answer

Heiberg picture Heiberg · Apr 24, 2012

You can either use your macro directly with hex integers like this:

UIColorFromRGB(0xff4433)

Or you can parse the hex-string into an integer like this:

unsigned colorInt = 0;
[[NSScanner scannerWithString:hexString] scanHexInt:&colorInt];
UIColorFromRGB(colorInt)