iPhone Developer Tips Stats: Past 30 days - Pageviews: 88,766 Visitors: 61,679 Thank you everyone! Let's shoot for 100,000 by May. Pass it on...
|
Below are two macros I paste inside every new iPhone project. Besides saving a few keystrokes, they work well when using the color picker application. Let’s look at the macros first:
#define RGB(r, g, b)
[UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1]
#define RGBA(r, g, b, a)
[UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]
Here’s the code without/with the macro:
// Code without the macro
msgLabel.textColor =
[UIColor colorWithRed:255/255.0 green:251/255.0 blue:204/255.0 alpha:1];
// Or like this...
msgLabel.textColor = [UIColor colorWithRed:1.0 green:.98 blue:.8 alpha:1];
// Code with macro
msgLabel.textColor = RGB(255, 251, 204);
UIColor expects its parameters to be expressed as values in the range of 0.0 to 1.0, so I pass in the color value I’m looking for between 0 and 255, and let the macro do the math for me.
Let me show you how I use the macro with the color picker application. The figure below shows a screenshot of the color picker – at this point I have selected the color I am interested in, so I choose rgb from the dropdown menu.

From here, I copy the value from the field “Hex:”, paste this into my project and finish by changing rgb to RGB.
Comments
2 Responses to “UIColor Macros”
Leave Comment
Interesting approach, using a macro. Instead of this, I added a category to NSString to add a “hexColor” method, to convert a string to a UIColor object.
http://bit.ly/NSString-HexColor
That allows you to say something like:
NSString *colorStr = @”#ff03ca”;
UIColor *color = [colorStr colorFromHex];
Thanks or this. It was just what I needed!