1)// 要显示不同颜色的数字
NSString *numberStr = [NSString stringWithFormat:@"%@",@"喜泊客"];
// _myabel创建的label
[_myabel setAttributedText:[self attrStrFrom:[NSString stringWithFormat:@"我在 %@ 上班",121] numberStr:numberStr]]
// 新增特殊处理:数字 颜色
- (NSMutableAttributedString *)attrStrFrom:(NSString *)titleStr numberStr:(NSString *)numberStr
{
NSMutableAttributedString *arrString = [[NSMutableAttributedString alloc]initWithString:titleStr];
// 设置前面几个字串的格式:蓝色 16.0f字号
[arrString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16.0f],
NSForegroundColorAttributeName:[UIColor blueColor]
}
range:[titleStr rangeOfString:numberStr]];
return arrString;
}
优化:
/**
* @brief 关键字高亮的处理
* @category
* @param allString 整体字符串
* @param colorStr; 要改变颜色的字符串
* @param color; 要设置的颜色
* @param font; 字号
**/
- (NSMutableAttributedString*)attrStrFrom:(NSString*)allStringcolorStr:(NSString*)colorStrcolor:(UIColor*)colorfont:(UIFont*)font
{
NSMutableAttributedString*arrString = [[NSMutableAttributedStringalloc]initWithString:allString];
// 设置前面几个字串的格式:字号字体、颜色
[arrStringaddAttributes:@{NSFontAttributeName:font,
NSForegroundColorAttributeName:color
}
range:[allStringrangeOfString:colorStr]];
returnarrString;
}