Skip to content

Instantly share code, notes, and snippets.

@mschulkind
Created October 3, 2011 03:20
Show Gist options
  • Select an option

  • Save mschulkind/1258368 to your computer and use it in GitHub Desktop.

Select an option

Save mschulkind/1258368 to your computer and use it in GitHub Desktop.
UIColor from string
+ (UIColor*)colorFromString:(NSString*)colorString
{
UIColor* color;
if ([colorString characterAtIndex:0] == '#') {
unsigned int hexValue;
[[NSScanner scannerWithString:[colorString substringFromIndex:1]]
scanHexInt:&hexValue];
NSInteger red, green, blue;
switch([colorString length]) {
case 4:
red = ((hexValue & 0xF00) >> 4) + ((hexValue & 0xF00) >> 8);
green = (hexValue & 0xF0) + ((hexValue & 0xF0) >> 4);
blue = ((hexValue & 0xF) << 4) + (hexValue & 0xF);
break;
case 7:
red = (hexValue & 0xFF0000) >> 16;
green = (hexValue & 0xFF00) >> 8;
blue = hexValue & 0xFF;
break;
default:
NSLog(@"Invalid hex color code '%@'.", colorString);
assert(false);
}
color = [UIColor colorWithRed:red/255.0
green:green/255.0
blue:blue/255.0
alpha:1.0];
} else {
NSString* methodName = [NSString stringWithFormat:@"%@Color", colorString];
SEL selector = NSSelectorFromString(methodName);
if (![UIColor respondsToSelector:selector]) {
NSLog(@"Color '%@' not found.", colorString);
assert(false);
}
color = [UIColor performSelector:selector];
}
return color;
}
@mschulkind
Copy link
Copy Markdown
Author

Accepts strings like: 'green', 'red', 'groupedTableViewBackground', '#934', '#fcfcfc', '#123456', etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment