Created
October 3, 2011 03:20
-
-
Save mschulkind/1258368 to your computer and use it in GitHub Desktop.
UIColor from string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| + (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; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Accepts strings like: 'green', 'red', 'groupedTableViewBackground', '#934', '#fcfcfc', '#123456', etc.