Skip to content

Instantly share code, notes, and snippets.

@hlung
Last active December 30, 2020 20:59
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save hlung/ab9c71c2e98d5da845aa to your computer and use it in GitHub Desktop.
Make UIColor support hex color codes
//
// UIColor+PXExtensions.h
// Creates UIColor from hex string. "#" prefix is optional. Supports 3 and 6 hex digits.
// Originally from http://pixelchild.com.au/post/12785987198/how-to-convert-a-html-hex-string-into-uicolor-with
// But that link seems to be broken.
// Revived by Thongchai Kolyutsakul (21 May 2015).
//
// USAGE: UIColor *mycolor = [UIColor pxColorWithHexValue:@"#BADA55"];
// UIColor *mycolor = [UIColor pxColorWithHexValue:@"FFFFFF"];
// UIColor *mycolor = [UIColor pxColorWithHexValue:@"1AD"];
//
#import <UIKit/UIKit.h>
@interface UIColor (UIColor_PXExtensions)
+ (UIColor*)pxColorWithHexValue:(NSString*)hexValue;
@end
//
// UIColor+PXExtensions.m
//
#import "UIColor+UIColor_PXExtensions.h"
@implementation UIColor (UIColor_PXExtensions)
+ (UIColor*)pxColorWithHexValue:(NSString*)hexValue
{
//Default
UIColor *defaultResult = [UIColor blackColor];
//Strip prefixed # hash
if ([hexValue hasPrefix:@"#"] && [hexValue length] > 1) {
hexValue = [hexValue substringFromIndex:1];
}
//Determine if 3 or 6 digits
NSUInteger componentLength = 0;
if ([hexValue length] == 3)
{
componentLength = 1;
}
else if ([hexValue length] == 6)
{
componentLength = 2;
}
else
{
return defaultResult;
}
BOOL isValid = YES;
CGFloat components[3];
//Seperate the R,G,B values
for (NSUInteger i = 0; i < 3; i++) {
NSString *component = [hexValue substringWithRange:NSMakeRange(componentLength * i, componentLength)];
if (componentLength == 1) {
component = [component stringByAppendingString:component];
}
NSScanner *scanner = [NSScanner scannerWithString:component];
unsigned int value;
isValid &= [scanner scanHexInt:&value];
components[i] = (CGFloat)value / 256.0f;
}
if (!isValid) {
return defaultResult;
}
return [UIColor colorWithRed:components[0]
green:components[1]
blue:components[2]
alpha:1.0];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment