I want to create UIColor from HEX value. But my Color is a NSString. So i implement this solution: How can I create a UIColor from a hex string?
code:
#define UIColorFromRGB(rgbValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
And then i have (simplify):
NSString *myString = [[NSString alloc] initWithString:@"0xFFFFFF"];
So when i want to call macro:
UIColor *myColor = UIColorFromRGB(myString);
I'm getting an error: invalid operands to binary expression ('NSString *' and 'int')
So i know i have to pass int, but how to convert NSString to int in this case? Of course [myString intValue];
does not work here.
To convert a UIColor instance to a hex value, we define a convenience method, toHex(alpha:) . The method accepts one parameter of type Bool , which indicates whether the alpha value should be included in the string that is returned from the method.
You can either use your macro directly with hex integers like this:
UIColorFromRGB(0xff4433)
Or you can parse the hex-string into an integer like this:
unsigned colorInt = 0;
[[NSScanner scannerWithString:hexString] scanHexInt:&colorInt];
UIColorFromRGB(colorInt)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With