iOS 将颜色NSString转换为UInt32

有时候,我们在开发应用的时候,需要将得到的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

 *  GitHubhttps://github.com/JnKindle

 *  cnblogshttp://www.cnblogs.com/JnKindle

 */

 

你可能感兴趣的:(iOS,iPhone应用开发,iPad应用开发)