/**
* 拼接字符串
*/
-(NSMutableAttributedString *)obtainResultWithColorAndStringDictionary:(NSDictionary *)dic
{
NSMutableAttributedString * result = [[NSMutableAttributedString alloc] init];
NSArray * keys = [dic allKeys];
for (int i = 0; i < keys.count; i++) {
NSString * color = [dic objectForKey:[keys objectAtIndex:i]];
NSString * content = [keys objectAtIndex:i];
[result appendAttributedString:[self getNewAttributedStringWith:color And:content]];
}
return result;
}
/**
* 创建有颜色的字符串
*/
-(NSAttributedString *)getNewAttributedStringWith:(NSString *)hexColor And:(NSString *)contents
{
UIColor * color = [self colorWithHexString:hexColor];
NSAttributedString * attrString = [[NSAttributedString alloc] initWithString:contents attributes:@{NSForegroundColorAttributeName:color}];
return attrString;
}
/**
* 十六进制 转颜色
*/
-(UIColor *)colorWithHexString:(NSString *)color
{
//去掉后面的空格和换行
NSString * colorString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if (colorString.length < 6) {
return [UIColor clearColor];
}
//去除前缀
if ([colorString hasPrefix:@"0X"]) {
colorString = [colorString substringFromIndex:2];
}else if ([colorString hasPrefix:@"#"]) {
colorString = [colorString substringFromIndex:1];
}else if (colorString.length != 6) {
return [UIColor clearColor];
}
//分割字符串,取出red green blue
NSRange range;
range.location = 0;
range.length = 2;
NSString * redString = [colorString substringWithRange:range];
range.location = 2;
NSString * greenString = [colorString substringWithRange:range];
range.location = 4;
NSString * blueString = [colorString substringWithRange:range];
//scan values
unsigned int red,green,blue;
[[NSScanner scannerWithString:redString] scanHexInt:&red];
[[NSScanner scannerWithString:greenString] scanHexInt:&green];
[[NSScanner scannerWithString:blueString] scanHexInt:&blue];
return [UIColor colorWithRed:((float)red / 255.0) green:((float)green / 255.0) blue:((float)blue / 255.0) alpha:1.0];
}