有時候,我們在開發應用的時候,需要將得到的Json數據轉換爲我們所需要的類型,這裏將介紹怎麼將顏色NSString轉換爲UInt32。
例如,數據爲#FFC000
//將#替換爲0x
NSString *typeColor = [allchant.ind_color stringByReplacingOccurrencesOfString:@"#" withString:@"0x"];
//NSString轉爲UInt32
NSScanner *scanner = [NSScanner scannerWithString:typeColor];
unsigned hexNum;
[scanner scanHexInt:&hexNum];
self.backgroundColor = HEX_COLOR(hexNum);
附:
#define HEX_COLOR(h) [UIColor colorWithRGBHex:(h)]
+ (UIColor *)colorWithRGBHex:(UInt32)hex {
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];
}
/**
* Author:Jn
* GitHub:https://github.com/JnKindle
* cnblogs:http://www.cnblogs.com/JnKindle
*/