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];
}
相关推荐
茯苓gao13 小时前
嵌入式开发笔记:QSerialPort 完整使用指南——从基础 API 到工程实战
笔记·嵌入式硬件·qt·学习
min(a,b)13 小时前
学习第 6 天:类型注解、装饰器与高级特性
python·学习
minglie113 小时前
线性电枢和分圆多项式
学习
汉堡包00113 小时前
【工具分享】--威胁情报平台大全
学习·安全·web安全·信息安全
库奇噜啦呼15 小时前
【iOS】weak底层实现
macos·ios·cocoa
旺仔学长 哈哈15 小时前
55384 消防安全教育与逃生演练小程序:知识学习、案例浏览和在线演练一站式实现
学习·小程序·消防教育·逃生演练
jike_202615 小时前
iPhone会议录音转文字怎么操作?科会通实测:支持离线录音与多人声纹识别的苹果AI会议纪要工具
人工智能·cocoa·iphone
今夜有雨.15 小时前
C++JSON 解析器
c++·笔记·后端·学习·json
Mr+范15 小时前
电源诱骗芯片CH224K
单片机·学习
幸福在路上wellbeing16 小时前
AI 智能体开发 · Day 1 详细学习手册
人工智能·学习