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];
}
相关推荐
不灭锦鲤8 分钟前
网络安全学习第101天
学习
承渊政道11 分钟前
【动态规划算法】(背包问题经典模型与解题套路)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
遗憾随她而去.42 分钟前
Java学习(一)
java·开发语言·学习
sealaugh321 小时前
react native(学习笔记第三课) 英语打卡微应用(2)-从上传图片开始
笔记·学习·react native
北冥有鱼被烹2 小时前
【玩索】【英语武器系统之1】用塞尔达武器系统学习英语语法
学习·english
老蒋每日coding2 小时前
Node.js 安装指南(Mac 版本)
macos·node.js
AI玫瑰助手2 小时前
Python入门:Windows/macOS/Linux系统安装Python教程
windows·python·macos
智算菩萨2 小时前
OpenAI Codex 国内使用完全指南:Windows/macOS/Linux 三平台详细安装配置教程(现在最新的有gpt-5.3-codex和gpt-5.4)
linux·windows·gpt·macos·ai·ai编程·codex
AAI机器之心2 小时前
在 macOS 上本地部署 Ollama + LLaMA3(附教程)
人工智能·macos·langchain·llm·知识库·大模型部署
HSTK2 小时前
Mac上配置PlatformIO
macos