创建分类 #import"UILabel+AutoSet.h" 此分类目的是实现对一个UILabel中的字体大小颜色进行改变。
使用方法,在使用的地方引用头文件 #import "UILabel+AutoSet.h" 或者 直接放到PrefixHeader文件中去。
NSArray * arr = @[@[@"标题1",@"686868",@"15"],@[@"标题2",@"ff8722",@"15"]];
[self.myLabel getLabelUIWithArray:arr];
使用时注意事项:参数数组中的值不可以为空,不然就会报数组内对象为空的错误。
#import
@interface UILabel (AutoSet)
-(void)getLabelUIWithArray:(NSArray *)AutoArr;
@end
#import "UILabel+AutoSet.h"
@implementation UILabel (AutoSet)
-(void)getLabelUIWithArray:(NSArray *)AutoArr;
{
// 此数组所传值格式必须为 @[@[文字,颜色,字体],@[文字,颜色,字体],@[文字,颜色,字体]];颜色需为RGB十六进制格式字符串,字体为字号,也是字符串格式 例: NSArray * arr = @[@[@"标题1",@"686868",@"15"],@[@"标题2",@"ff8722",@"15"]];
NSMutableString * allStr = [[NSMutableStringalloc] init];
for (int i =0;i < AutoArr.count; i++) {
[allStr appendString:[NSStringstringWithFormat:@"%@",AutoArr[i][0]]];
}
NSMutableAttributedString * mostStr = [[NSMutableAttributedStringalloc] initWithString:allStr];
int j = 0;
for (int i =0;i < AutoArr.count; i++) {
NSString * str = AutoArr[i][0];
UIColor * myColor = [selfgetColor:AutoArr[i][1]];
UIFont * font = [UIFontsystemFontOfSize:[AutoArr[i][2]floatValue]];
NSRange range = NSMakeRange(j, str.length);
j += str.length;
[mostStr addAttribute:NSForegroundColorAttributeNamevalue:myColor range:range];//设置字体颜色
[mostStr addAttribute:NSFontAttributeNamevalue:font range:range];//设置字体字号和字体类别
}
self.attributedText = mostStr;
}
- (UIColor *) getColor:(NSString *)hexColor{
unsigned int red, green, blue;
NSRange range;
range.length =2;
range.location =0;
[[NSScannerscannerWithString:[hexColor substringWithRange:range]]scanHexInt:&red];
range.location =2;
[[NSScannerscannerWithString:[hexColor substringWithRange:range]]scanHexInt:&green];
range.location =4;
[[NSScannerscannerWithString:[hexColor substringWithRange:range]]scanHexInt:&blue];
return [UIColorcolorWithRed:(float)(red/255.0f)green:(float)(green/255.0f)blue:(float)(blue/255.0f)alpha:1.0f];
}
@end