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];
}
相关推荐
小心亦新1 小时前
STM32学习16--定时器输出比较2直流电机
stm32·嵌入式硬件·学习
themingyi1 小时前
Abaqus PythonReaderPro
学习
zengorange1 小时前
Dart语言
学习·flutter
一只小菜鸡..2 小时前
Stanford CS144 学习笔记 (七):跨越虚实的边界——物理层、链路层与无线网络
网络·笔记·学习
YM52e3 小时前
鸿蒙Flutter Stack堆叠布局:实现多层级界面
学习·flutter·华为·harmonyos·鸿蒙·鸿蒙系统
_瑞3 小时前
AI Coding 那么快,为什么还需要 SDD?
人工智能·ios·ai编程
HYDtomako3 小时前
Claude Code学习
学习·ai·agent·claude code
AOwhisky4 小时前
Python 学习笔记(第十一期)——运维自动化(上·后篇):进程级监控与子进程管理——psutil进阶
运维·开发语言·python·学习·云原生·运维开发
之歆4 小时前
从 Mac 回到 Windows:用 PowerToys + AutoHotkey 找回熟悉手感
windows·macos
轩辕十四leo4 小时前
Astrolabe(星盘):让 AI 看见自己写出的 UI
ios·ai编程