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];
}
相关推荐
IT古董1 小时前
【MES学习笔记系列】05 - MES 数据库设计
笔记·学习·mes
LATASA2 小时前
【 从0到1构建 Agent Harness学习笔记】
网络·笔记·学习
weixin_431600443 小时前
做 Agent 会用到的 Node API(3):异步与流
前端·学习·ai·agent·ai编程
70asunflower4 小时前
Triton 从 0 到 1 完整学习教程
学习·triton
天国梦4 小时前
2026年英语教学数字化工具深度测评:天学网、腾讯英语君、翼课网横向对比
人工智能·学习
YH55269844 小时前
MacBook Air M4 和 M5 怎么选?
macos
GitLqr5 小时前
iOS 27 强制要求 UISceneDelegate:UIKit 和 Flutter 开发者该如何应对?
flutter·ios·全栈
MoSTChillax5 小时前
数字人竞品分析(中):核心功能、产品使用与技术能力对比
ide·macos·xcode
oier_Asad.Chen5 小时前
【OI学习笔记】Floyed-Warshall算法解决传递闭包问题
c++·笔记·学习·算法·图论·最短路·传递闭包
鱼听禅6 小时前
C#学习笔记-添加编译参数到程序集自动更新程序编译时间
笔记·学习·c#