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];
}
相关推荐
巴博尔6 小时前
UNIAPP中NVUE页面 动画
android·前端·javascript·ios·uni-app
ServBay7 小时前
2026 Mac 本地大模型部署深度解析与混合架构指南
后端·macos·aigc
小新同学^O^7 小时前
简单学习 --> 模型参数
学习·llm·大模型参数
cdbqss17 小时前
VB2026 菜单生成基类 BqGetMenuStrip
数据库·经验分享·学习·oracle·vb
2601_955767428 小时前
圆偏振光膜与AR抗反射膜原理评测:scinique双护技术如何实现“一柔一清”?
ios·ar·iphone·圆偏振光·磁控溅射
人月神话-Lee8 小时前
【图像处理】图像导出与工业级压缩策略——从像素到文件的最后一公里
图像处理·人工智能·ios·ai编程·swift
吃好睡好便好9 小时前
创建魔方矩阵和单位矩阵
开发语言·人工智能·学习·线性代数·matlab·矩阵
星夜夏空999 小时前
STM32单片机学习(21) —— I2C通信
stm32·单片机·学习
searchforAI11 小时前
B站视频转笔记用哪个工具?2026年四款AI笔记工具对比实测
人工智能·经验分享·笔记·gpt·学习·视频总结·ai笔记
爱上好庆祝12 小时前
学习JS第十一天(JS的进阶)
前端·javascript·学习