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];
}
相关推荐
坤坤子吖7 分钟前
C++智能指针:RAII、shared_ptr与内存泄漏
开发语言·c++·笔记·学习
词却2 小时前
OpenCV学习:MediaPipe 人脸网格检测
opencv·学习
李日华大战鸡红2 小时前
FOC SVPWM过调制(学习记录)
stm32·单片机·学习
AI职业加油站2 小时前
AI 校招现状:大模型应用工程师证书,助力简历能力证明
大数据·运维·人工智能·学习·职场发展
Anhty2 小时前
2026最新免费手机音频处理工具 !!
android·功能测试·ios·智能手机·音视频
陈年老古董3 小时前
Hive 函数学习笔记(上):单行函数与炸裂函数
hive·笔记·学习
喜欢打篮球的普通人4 小时前
MiniMind 学习笔记(十八):速通强化学习——从 MDP 到 PPO 的概念与算法地图
笔记·深度学习·学习
老王爱玩车4 小时前
动态内存管理
c语言·开发语言·学习·面试
2501_915909065 小时前
iOS应用从开发到上架App Store的完整发布流程与步骤指南
android·ios·小程序·https·uni-app·webview
lvqinglou6 小时前
学习Sql-part1 for婷姐
sql·学习·性能优化