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];
}
相关推荐
all7980796973 小时前
黑苹果macos 15 Sequoia升级 macos 26.1 Tahoe小结
macos
●VON3 小时前
0基础也能行!「Flutter 跨平台开发训练营」1月19日正式启动!
学习·flutter·von·openjiuwen
敲敲了个代码3 小时前
如何优化批量图片上传?队列机制+分片处理+断点续传三连击!(附源码)
前端·javascript·学习·职场和发展·node.js
知识分享小能手4 小时前
Oracle 19c入门学习教程,从入门到精通,Oracle 其他数据对象 —— 语法详解与综合实践(11)
数据库·学习·oracle
唯一浩哥4 小时前
2026 年,macbook air 2015 升级注意事项
macos·macbook·macbook air 2015·升级硬盘
觉醒大王4 小时前
如何让综述自然引出你的理论框架?
论文阅读·深度学习·学习·自然语言处理·学习方法
知南x4 小时前
【华为昇腾DVPP/AIPP学习篇】(1)工程结构介绍
学习·华为·昇腾·cann·dvpp
科技林总5 小时前
【系统分析师】4.7 Web服务
学习
LaoZhangGong1236 小时前
学习TCP/IP的第6步:断开连接
网络·学习·tcp/ip·以太网
TheNextByte16 小时前
如何将文件从Android无线传输到 iPad
android·ios·ipad