instead of a macro I wrote a category for this. It handles RGB(A) value strings with the formats @"#17BAFA(FF)", @"#ABC(F)", @"17BAFA", @"0xABC",…
As it uses message sending, rather than a macro call, it feels more natural in the context of Objective-C.
Use it like UIColor *color = [UIColor colorFromHexString:@"#DCDFE3"];
afterwards you can check if(!color) { // must be an invalid format
@implementation UIColor (Creation) +(UIColor *)_colorFromHex:(NSUInteger)hexInt { int r,g,b,a; r = (hexInt >> 030) & 0xFF; g = (hexInt >> 020) & 0xFF; b = (hexInt >> 010) & 0xFF; a = hexInt & 0xFF; return [UIColor colorWithRed:r / 255.0f green:g / 255.0f blue:b / 255.0f alpha:a / 255.0f]; } +(UIColor *)colorFromHexString:(NSString *)hexString { hexString = [hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; if ([hexString hasPrefix:@"#"]) hexString = [hexString substringFromIndex:1]; else if([hexString hasPrefix:@"0x"]) hexString = [hexString substringFromIndex:2]; int l = [hexString length]; if ((l!=3) && (l!=4) && (l!=6) && (l!=8)) return nil; if ([hexString length] > 2 && [hexString length]< 5) { NSMutableString *newHexString = [[NSMutableString alloc] initWithCapacity:[hexString length]*2]; [hexString enumerateSubstringsInRange:NSMakeRange(0, [hexString length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { [newHexString appendFormat:@"%@%@", substring, substring]; }]; hexString = newHexString; } if ([hexString length] == 6) hexString = [hexString stringByAppendingString:@"ff"]; NSScanner *scanner = [NSScanner scannerWithString:hexString]; unsigned hexNum; if (![scanner scanHexInt:&hexNum]) return nil; return [self _colorFromHex:hexNum]; } @end
When I pick the keyboards background color with Photoshop, the value is "0xD9DCE0", not "0xDCDFE3".