之前遇到一个商品打折,需要显示原价已经废除的功能,查了一些资料,各种各样的自定义添加。
其实系统自带的NSMutableAttributedString
就能实现这个功能,废话不多说。看代码:
一个label不同颜色不同字体显示
NSMakeRange(x,y)
x:从哪个位置开始 y:从那个位置开始后几个位置
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"预订瑜伽*1节"];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0,2)];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(2,5)];//设置颜色
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldMT" size:20] range:NSMakeRange(0,2)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldMT" size:15] range:NSMakeRange(2,5)];//设置字体
cell_total.classLabel.attributedText = str;
删除线
NSString *oldPriceString = [NSString stringWithFormat:@"原价:%d元",oldPrice];
NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:oldPriceString];
[attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, oldPriceString.length)];
label.attributedText = attri;