新建一个类命名为UIColor+Hex,在其中添加类方法实现扩展。
在.h文件中
写一个类方法
+ (UIColor *)colorForHex:(NSString *)hexColor;
.m文件中实现
@implementation UIColor (Utils)
+ (UIColor *)colorForHex:(NSString *)hexColor{
NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [hexColor substringWithRange:range];
range.location = 2;
NSString *gString = [hexColor substringWithRange:range];
range.location = 4;
NSString *bString = [hexColor substringWithRange:range];
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f)
green:((float) g / 255.0f)
blue:((float) b / 255.0f)
alpha:1.0f];
}
@end
在其他类中如果使用,首先包含头文件,然后直接调用。
例如tabBar.tintColor = [UIColor colorForHex:@"26a6d7"];