十六进制函数转换UIColor对象

在实际开发中 有时美工会给我们一种颜色值(形如#FF0000)去设置某个view的背景色,这时我们需要把这种十六进制的值转换为UIColor对象

下面这个方法就很有用了:

- (UIColor *) stringTOColor:(NSString *)str  

{  

if (!str || [str isEqualToString:@""]) {  

return nil;  

    }  

  unsigned red,green,blue;  

 NSRange range;  

 range.length = 2;  

 range.location = 1;  

 [[NSScanner scannerWithString:[str substringWithRange:range]] scanHexInt:&red];  

 range.location = 3;  

[[NSScanner scannerWithString:[str substringWithRange:range]] scanHexInt:&green];  

 range.location = 5;  

 [[NSScanner scannerWithString:[str substringWithRange:range]] scanHexInt:&blue];    UIColor *color= [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:1];

return color;  

}  

原文地址:https://www.cnblogs.com/billy-chou/p/3966671.html