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];
}
相关推荐
小新同学^O^5 分钟前
Redis的简单总结
数据库·redis·学习
garmin Chen8 分钟前
LeetcodeHot100打卡(14、合并空间,15、轮转数组,16、除了自身以外数组乘积,17.缺失的第一个整数)
java·笔记·学习·算法
不羁的木木1 小时前
ArkWeb实战学习笔记04-JavaScript与Native通信
笔记·学习·harmonyos
li星野1 小时前
RAG优化系列:HyDE(假设文档嵌入)——让LLM先写答案再检索
python·学习
知识分享小能手1 小时前
Flask入门学习教程,从入门到精通,Flask智能租房——用户中心知识点详解(9)
python·学习·flask
魔法阵维护师2 小时前
从零开发游戏需要学习的c#模块,第三十一章(技能冷却系统 —— 范围爆炸)
学习·游戏·c#
试剂界的爱马仕2 小时前
《古董局·终局5:潮生》第 4 章:藤田的棋局
人工智能·学习
帅次2 小时前
讯飞与腾讯云:Android 实时语音识别服务对比选择
android·ios·微信小程序·小程序·android studio·android runtime
searchforAI2 小时前
我的Obsidian知识库,现在可以自动剪藏笔记到本地了
人工智能·笔记·学习·音视频·ai工具·obsidian·视频总结
周末也要写八哥2 小时前
Visual C++6.0下载安装流程及PDF学习手册资源
c++·学习·pdf