1、传入字符串数组,通过NSMutableAttributedString修改匹配文字
可以根据需要搞成匹配单个字符串
- (NSAttributedString *)applyFontSizeToText:(NSString *)text matchStrings:(NSArray<NSString *> *)matchStrings {
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
UIFont *font = [UIFont systemFontOfSize:16]; // 目标字体大小
for (NSString *match in matchStrings) {
NSRange searchRange = NSMakeRange(0, text.length);
NSRange foundRange;
while (searchRange.location < text.length &&
(foundRange = [text rangeOfString:match options:NSCaseInsensitiveSearch range:searchRange]).location != NSNotFound) {
[attributedString addAttribute:NSFontAttributeName value:font range:foundRange];
[attributedString addAttribute:NSForegroundColorAttributeName value:HexColor(@"#9B9B9B") range:foundRange];
// 更新搜索范围,避免死循环
searchRange = NSMakeRange(NSMaxRange(foundRange), text.length - NSMaxRange(foundRange));
}
}
return attributedString;
}
调用方法:
NSArray *matchArray = @[@"次/分钟", @"次", @"mmhg", @"小时", @"分钟"];
if (dataString.length != 0) {//避免空字符串
self.dataLabel.attributedText = [self applyFontSizeToText:self.dataLabel.text matchStrings:matchArray];
}