美文网首页
UIColor支持16进制颜色设置

UIColor支持16进制颜色设置

作者: 不是公主但有病 | 来源:发表于2016-01-05 15:26 被阅读220次

新建一个类命名为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"];

相关文章

网友评论

      本文标题:UIColor支持16进制颜色设置

      本文链接:https://www.haomeiwen.com/subject/ehrzhttx.html