How can I create a UIColor
from a hexadecimal string format, such as #00FF00
?
I ended up creating a category for UIColor
that I can just reuse in my other projects, and added this function:
+ (UIColor *)colorFromHex:(unsigned long)hex
{
return [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16))/255.0
green:((float)((hex & 0xFF00) >> 8))/255.0
blue:((float)(hex & 0xFF))/255.0
alpha:1.0];
}
The usage goes like:
UIColor *customRedColor = [UIColor colorFromHex:0x990000];
This is far faster than passing on a string and converting it to a number then shifting the bits.
You can also import the category from inside your .pch
file so you can easily use colorFromHex
everywhere in your app like it's built-in to UIColor
:
#ifdef __OBJC__
#import
#import
// Your other stuff here...
#import "UIColor+HexColor.h"
#endif