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

 */

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章