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];
}
相关推荐
Young Doro5 小时前
独立性检测学习任务
人工智能·学习·数据挖掘
snakecy6 小时前
macOS 安装 LaTeX 全流程指南:从 MacTeX 到中文排版
macos·策略模式
终端安全笔记6 小时前
一份配置管十项 AI 功能:它关的是入口,不是数据
网络安全·ios·移动设备管理
卡卡~~6 小时前
“101计划”核心课程实践教材《数据实验结构指导-C++语言版》题目集
开发语言·c++·学习·算法
lengxuenong7 小时前
树状数组 · 信息学学习手册1-求和3个模板
c++·学习·算法·青少年编程
lanxiaoqing028 小时前
演讲训练的第一步:先敢说,再会说
人工智能·学习·学习方法·口才
m4Rk_10 小时前
【论文阅读】Agent记忆机制(109):MemComposer——用强化学习学会选哪些记忆、选多少以及怎样排序
论文阅读·人工智能·学习·开源·github
zhangdaliangmvp10 小时前
快速排序的学习理解:从基础分治到三路划分优化
c++·学习·算法
叼烟扛炮10 小时前
Linux 学习笔记(四):文件检索与管道重定向
linux·笔记·学习
王夏奇10 小时前
AI工具学习
网络·学习