views:

263

answers:

4

Like the title says I want to use a color code instead of doing something like this

lblTemp.textColor = [UIColor colorWithRed: 0 green:0x99/255.0 blue:0 alpha:1.0];

for instance I have the following colorcode #30ae36 how can I use this one instead of doing the above.

+2  A: 

UIColor doesn't offer a default method for that, but, you could create a so called category for UIColor which takes the hex value (sans the #) and turns it in to the corresponding RGB components and uses those components to feed to UIColor's colorWithRed:green:blue:alpha:.

MathieuK
it's been figured out.... I'm blind as a bat I'll post the answer below Thanks for your input though
jovany
A: 

this should do the trick for this code #30ae36

lblTemp4.textColor = [UIColor colorWithRed:0x*30*/255.0 green:0x*AE*/255.0 blue:0x*36*/255.0 alpha:1.0];
jovany
+3  A: 

I use this handy 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]

(I might have gotten it from here, but you can find it in many places. In any case it's worth reading the discussion about macros vs inline functions at this link.)

If you want to initialize the color from a string (for example from a plist), you can use this:

unsigned    rgbValues;
[[NSScanner scannerWithString:@"0xFF0000"] scanHexInt: &rgbValues];
UIColor* redColor = UIColorFromRGB(rgbValues);
Felixyz
thanks for the extra info.
jovany
A: 

In the previous answer, from jovany the * * stars should be omitted. So #30ae36 becomes:

lblTemp4.textColor = [UIColor colorWithRed:0x30/255.0 green:0xAE/255.0 blue:0x36/255.0 alpha:1.0];

(Maybe obvious, but I didn´t get it at first sight)

Olof