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];
}
相关推荐
艾莉丝努力练剑16 小时前
【AI大模型接入SDK】LLM会话管理模块设计
网络·c++·人工智能·学习·大模型
萧行之17 小时前
可视化技术复盘:从图形语法看 D3、Vega-Lite、ECharts、Observable Plot
前端·学习·数据可视化
小弥儿1 天前
GitHub今日热榜 | 2026-09-15:AI 智能体与本地生成工具领跑
学习·开源
susplus1 天前
【初识ARM】ARM相关基础概念
学习·arm
XiHongShi20161 天前
键盘大小写指示器(代替键盘灯)
学习·计算机
斯维赤1 天前
AI Agent学习之路 | Prompt Engineering(提示词工程)的三板斧核心技巧
人工智能·学习·prompt
2301_802651081 天前
imx6ull裸机开发:UART
学习
辣知1 天前
辣知·化智56 良渚神权与夏朝颠覆
学习
dadaobusi1 天前
学习:三层交换机
学习