How can I convert RGB hex string into UIColor in objective-c?
You're close but colorWithRed:green:blue:alpha: expects values ranging from 0.0 to 1.0, so you need to shift the bits right and divide by 255.0f:
CGFloat red = ((baseColor1 & 0xFF0000) >> 16) / 255.0f;
CGFloat green = ((baseColor1 & 0x00FF00) >> 8) / 255.0f;
CGFloat blue = (baseColor1 & 0x0000FF) / 255.0f;
EDIT - Also NSScanner's scanHexInt will skip past 0x in front of a hex string, but I don't think it will skip the # character in front of your hex string. You can add this line to handle that:
[scanner2 setCharactersToBeSkipped:[NSCharacterSet symbolCharacterSet]];
I added a string replacement so it accepts a hex string with or without the #
Possible full code:
+ (UIColor *)colorWithHexString:(NSString *)stringToConvert
{
NSString *noHashString = [stringToConvert stringByReplacingOccurrencesOfString:@"#" withString:@""]; // remove the #
NSScanner *scanner = [NSScanner scannerWithString:noHashString];
[scanner setCharactersToBeSkipped:[NSCharacterSet symbolCharacterSet]]; // remove + and $
unsigned hex;
if (![scanner scanHexInt:&hex]) return nil;
int r = (hex >> 16) & 0xFF;
int g = (hex >> 8) & 0xFF;
int b = (hex) & 0xFF;
return [UIColor colorWithRed:r / 255.0f green:g / 255.0f blue:b / 255.0f alpha:1.0f];
}