处理所有整数字部分加大:
//处理所有整数字部分加大,如:"拼团价:¥777.77-¥888.88-¥999.99"
+ (NSAttributedString *)formattedPriceFromString:(NSString *)text {
NSMutableAttributedString *result = [[NSMutableAttributedString alloc] initWithString:text];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d+)(\\.\\d+)?|[^\\d]" options:0 error:nil];
UIFont *largeFont = [UIFont boldSystemFontOfSize:18];
UIFont *smallFont = [UIFont systemFontOfSize:12];
// 设置默认字体为 smallFont
[result addAttribute:NSFontAttributeName value:smallFont range:NSMakeRange(0, text.length)];
// 查找并设置数字部件的largeFont
NSArray<NSTextCheckingResult *> *matches = [regex matchesInString:text options:0 range:NSMakeRange(0, text.length)];
for (NSTextCheckingResult *match in matches) {
// 整数部分
NSRange intRange = [match rangeAtIndex:1];
if (intRange.location != NSNotFound) {
[result addAttribute:NSFontAttributeName value:largeFont range:intRange];
}
// 小数部分
NSRange fracRange = [match rangeAtIndex:2];
if (fracRange.location != NSNotFound) {
[result addAttribute:NSFontAttributeName value:smallFont range:fracRange];
}
}
return result;
}
使用:
NSString *priceStr = @"拼团价¥888.88-¥999.99";
NSAttributedString *attr = [Tools formattedPriceFromString:priceStr];
self.priceLabel.attributedText = attr;
实现效果:
2个.png
无数个都可以.png
总之:
只有是数字并且是整数部分,字号才被加大,其他部分一律小字体!