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];
}
相关推荐
m4Rk_14 小时前
【论文阅读】Agent 记忆机制(22):FluxMem——根据对话结构动态选择记忆组织方式
论文阅读·人工智能·学习
天国梦15 小时前
英语词汇学习软件深度测评:天学网等三款APP实测对比与选型指南
学习
菜鸟‍15 小时前
【论文学习】Frontiers in Physics 2024 || Cap2Seg:基于文本描述生成的 COVID-19 医学图像分割性能提升方法
人工智能·学习
MartinYeung517 小时前
[论文学习]The Instruction Hierarchy:训练LLM优先处理特权指令
人工智能·深度学习·学习
晓梦林17 小时前
[Dest0g3 520迎新赛]EasyPHP-学习笔记
android·笔记·学习
我想我不够好。18 小时前
2026.7.28 消防学习 1.5hour
学习
芳草萋萋鹦鹉洲哦18 小时前
【git】重新生成并添加 SSH Key(Mac)
git·macos·ssh
吃好睡好便好18 小时前
MATLAB中图像格式的转换
开发语言·图像处理·学习·计算机视觉·matlab
秋田君18 小时前
Qt_常用控件使用学习
数据库·qt·学习
小黄蚁18 小时前
LVGL学习笔记(一)
笔记·学习