iPhone UIColor got you down? Try this on for size…

iPhone UIColor got you down? Try this on for size…

Jonas Schnelli has a good UIColor implementation for Objective-C which will allow you to use Hex colors for UIColor, including alpha values… all by using an NSString implementation. Short, sweet, and it works like a charm. Check the link to the github location. If you’re interested in seeing what’s under the hood at the moment in the implementation (.m) file, here you go…

//label.textColor = [UIColor colorWithHexString:@"ff0000"]; // red color
//label.textColor = [UIColor colorWithHexString:@"f00"]; // red color
//label.textColor = [UIColor colorWithHexString:@"ff000055"]; // red color with some alpha
@implementation UIColor (i7HexColor)

+ (UIColor *)colorWithHexString:(NSString *)hexString {

	/* convert the string into a int */
	unsigned int colorValue;
	NSString *hexStringCleared = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
	if(hexStringCleared.length == 3) {
		/* short color form */
		/* im lazy, maybe you have a better idea to convert from #fff to #ffffff */
		hexStringCleared = [NSString stringWithFormat:@"%@%@%@%@%@%@", [hexStringCleared substringWithRange:NSMakeRange(0, 1)],[hexStringCleared substringWithRange:NSMakeRange(0, 1)],
												[hexStringCleared substringWithRange:NSMakeRange(1, 1)],[hexStringCleared substringWithRange:NSMakeRange(1, 1)],
												[hexStringCleared substringWithRange:NSMakeRange(2, 1)],[hexStringCleared substringWithRange:NSMakeRange(2, 1)]];
	}
	if(hexStringCleared.length == 6) {
		hexStringCleared = [hexStringCleared stringByAppendingString:@"ff"];
	}
	[[NSScanner scannerWithString:hexStringCleared] scanHexInt:&colorValue];

	/* now build the UIColor with standard allocators */
	return [UIColor colorWithRed:((colorValue)&0xFF)/255.0 
					green:((colorValue>>8)&0xFF)/255.0 
					 blue:((colorValue>>16)&0xFF)/255.0 
					alpha:((colorValue>>24)&0xFF)/255.0];

}

@end

One Reply to “iPhone UIColor got you down? Try this on for size…”

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.