我在用UILabel显示“95元 220元”这样的字符串时,删除线总是无法正常显示出来,后来才发现前面不用显示删除线的字符串需要设置它的删除线风格为NSUnderlineStyleNone才有效,代码如下:
NSString *discountPriceStr = @"95";
NSString *unitStr = @"元";
NSString *originalPriceStr = @"220";
NSString *spaceStr = @" ";
NSString *textStr = [NSString stringWithFormat:@"%@%@%@%@%@", discountPriceStr, unitStr, spaceStr, originalPriceStr, unitStr];
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:textStr];
[attributeString addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xff6b64) range:NSMakeRange(0, discountPriceStr.length)];
[attributeString addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x666666) range:NSMakeRange(discountPriceStr.length, textStr.length - discountPriceStr.length)];
[attributeString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10.0f] range:NSMakeRange(0, discountPriceStr.length)];
[attributeString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:8.0f] range:NSMakeRange(discountPriceStr.length, textStr.length - discountPriceStr.length)];
[attributeString addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlineStyleNone) range:NSMakeRange(0, discountPriceStr.length + unitStr.length + spaceStr.length)];
[attributeString addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(discountPriceStr.length + unitStr.length + spaceStr.length, originalPriceStr.length + unitStr.length)];
[attributeString addAttribute:NSStrikethroughColorAttributeName value:UIColorFromRGB(0x66666) range:NSMakeRange(discountPriceStr.length + unitStr.length + spaceStr.length, originalPriceStr.length + unitStr.length)];
_priceLabel.attributedText = attributeString;