iOS OC匹配多个文字修改颜色和字号

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];
}
相关推荐
西安老张(AIGC&ComfyUI)1 小时前
第034章:ComfyUI&AIGC一阶段学习总结及下阶段学习安排
学习·aigc
Lvan的前端笔记1 小时前
ios:版本号和Build构建号
ios
正经人_x4 小时前
学习日记43:FINO
学习
smartpi_ai5 小时前
离线语音识别的“数字变量“限制:为什么不能识别“20.5度“?
人工智能·语音识别·xcode
网络工程小王6 小时前
【HCIE-AI】11.模型 昇腾迁移适配-精度调试-性能调优
人工智能·学习·华为·迁移学习·昇腾
阿童木写作7 小时前
Python批量翻译亚马逊商品图实战教程
开发语言·python·xcode
一只小菜鸡..7 小时前
CMU 15-213 CSAPP:机器级编程与内存的暗黑魔法(Machine-Level)
笔记·学习
2601_960906727 小时前
科技“无人区”跋涉,难度高、不确定性大
windows·macos·pycharm·myeclipse
鹤卿1238 小时前
「iOS」3GShare总结
macos·ios·objective-c·cocoa
Lvan的前端笔记8 小时前
ios:区分 App Store / Ad Hoc / Development
ios