12

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.

Community
  • 1
  • 1
Jakub
  • 13,712
  • 17
  • 82
  • 139
  • By the way, you made an error in the masking values of the code you copied. Green should be (rgbValue & 0x00FF00), not (rgbValue & 0xFF00), and blue should be (rgbValue & 0x0000FF), not (rgbValue & 0xFF). I copied your code, and had quite a time figuring out the problem. Anyway, I learned a lot about bitwise shifting and adding from Doug Galante at https://medium.com/@Dougly/bitwise-shifting-swift-3-a85a6954fb05 – Elise van Looij Dec 04 '20 at 17:58

2 Answers2

19

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)
Heiberg
  • 5,507
  • 2
  • 26
  • 28
5

You can't do that as standard but check out my category on UIColor which has a method for doing that.

Your macro you've defined is expecting that to be an integer packed in RGB format. You're passing in a string, which is why it's not working.

mattjgalloway
  • 34,792
  • 12
  • 100
  • 110