PIXEL
DOCK

I like the smell of Swift in the morning…

UIColor+colorWithHex: a category to get an UIColor from a hexadecimal integer value or string

Posted: | Author: | Filed under: iOS, Objective-C | 5 Comments »

I always find it really cumbersome to instantiate an UIColor object from a hexadecimal color value. To make life a bit easier I wrote this category for the UIColor class:

Because I often need to convert a hex string (e.g. from a parsed XML file) to an UIColor I added 2 methods to this category. You can now get an UIColor from a hexadecimal uint value or an NSString that can have the 3 following formats: “0xFFFFFF“, “#FFFFFF” or “FFFFFF“.

Just add this category to your project and you can use it like this:

You can download the category here.

Feel free to use it.

5 Comments

  • 1

    Markus Heidtsaid at

    Thanks a lot.
    I added some convenience methods in my code:

    +(UIColor*)colorWithHexString:(NSString*)hexString {
    return [self colorWithHexString:hexString andAlpha:1.0];
    }

    +(UIColor*)colorWithHexValue:(uint)hexValue {
    return [self colorWithHexValue:hexValue andAlpha:1.0];
    }

  • 2

    adminsaid at

    Good idea, thanks!

  • 3

    Jason Jonessaid at

    I put this in my project — was going to code my own but figured there was someone out there that coded the same thing (as a category). Thanks man!

  • 4

    Ross Greinkesaid at

    Also go the other way:

    – (NSString *) hexStringFromColor {

    CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0;

    // iOS 5
    if ( [self respondsToSelector: @selector(getRed:green:blue:alpha:)] ) {
    [self getRed: &red green: &green blue: &blue alpha: &alpha];
    }
    else {
    const CGFloat *components = CGColorGetComponents( [self CGColor] );
    red = components[0];
    green = components[1];
    blue = components[2];
    alpha = components[3];
    }
    return [NSString stringWithFormat: @”#%02X%02X%02X”,
    (int) roundf( red * 255.0 ),
    (int) roundf( green * 255.0 ),
    (int) roundf( blue * 255.0 )];
    }

  • 5

    adminsaid at

    Nice one, Ross! Thanks for the contribution!


Leave a Reply