简体   繁体   English

Objective-C中的HEX值

[英]HEX value in Objective-C

I want to create UIColor from HEX value. 我想从HEX值创建UIColor。 But my Color is a NSString. 但是我的Color是一个NSString。 So i implement this solution: How can I create a UIColor from a hex string? 所以我实现了这个解决方案: 如何从十六进制字符串创建UIColor?

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') 我收到一个错误: 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? 所以我知道我必须传递int,但在这种情况下如何将NSString转换为int? Of course [myString intValue]; 当然[myString intValue]; does not work here. 在这里不起作用。

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)

You can't do that as standard but check out my category on UIColor which has a method for doing that. 你不能这样做作为标准,但检查我的类别UIColor有一个方法来做到这一点。

Your macro you've defined is expecting that to be an integer packed in RGB format. 您定义的宏期望是以RGB格式打包的整数。 You're passing in a string, which is why it's not working. 你传入一个字符串,这就是为什么它不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM