(1)// 要显示不同颜色的数字
NSString *numberStr = [NSString stringWithFormat:@"%d",121];
// _myabel创建的label
[_myabel setAttributedText:[self attrStrFrom:[NSString stringWithFormat:@"已有 %d 条反馈",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;
调用下面这个方法 其实是上面处理颜色方法的改进版
NSString *numberStr = [NSString stringWithFormat:@"%d",121];
// _myabel创建的label
[_myabel setAttributedText:[self attrStrFrom:[NSString stringWithFormat:@"已有 %d 条反馈",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;
}
效果:
(2)不同字号的字:
_priceLabel的font字号是大字号
// 价钱
NSString *price = [NSString stringWithFormat:@" ¥%@ ",@"188.0"];
_priceLabel.text = price;
[_priceLabel setAttributedText:[self attrStrFrom:price colorStr:@"¥" color:[UIColor whiteColor] font:[UIFont systemFontOfSize:14.0]]];
调用下面这个方法 其实是上面处理颜色方法的改进版
/**
* @brief 关键字高亮的处理
* @category
* @param allString 整体字符串
* @param colorStr; 要改变颜色的字符串
* @param color; 要设置的颜色
* @param font; 字号
**/
- (NSMutableAttributedString *)attrStrFrom:(NSString *)allString colorStr:(NSString *)colorStr color:(UIColor *)color font:(UIFont *)font
{
NSMutableAttributedString *arrString = [[NSMutableAttributedString alloc]initWithString:allString];
// 设置前面几个字串的格式:字号字体、颜色
[arrString addAttributes:@{NSFontAttributeName:font,
NSForegroundColorAttributeName:color
}
range:[allString rangeOfString:colorStr]];
return arrString;
}
效果如图