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];
}
相关推荐
一条破秋裤2 小时前
零样本学习指标
深度学习·学习·机器学习
0xAaron2 小时前
确定crash文件和dSYM是否对应
ios·uuid·crash·dsym
喜欢踢足球的老罗2 小时前
Qoder AI IDE深度体验:用Repo Wiki与AskModel重塑开源库学习范式
人工智能·学习·qoder
可可苏饼干2 小时前
NoSQL 与 Redis
数据库·redis·笔记·学习·nosql
重生之我在番茄自学网安拯救世界3 小时前
网络安全中级阶段学习笔记(一):DVWA靶场安装配置教程与网络空间搜索语法
笔记·学习·网络安全·靶场·dvwa·fofa·google hack
源代码•宸3 小时前
GoLang并发简单例子(goroutine + channel + WaitGroup)
开发语言·经验分享·后端·学习·golang
TL滕3 小时前
从0开始学算法——第五天(初级排序算法)
数据结构·笔记·学习·算法·排序算法
走在路上的菜鸟3 小时前
Android学Dart学习笔记第十节 循环
android·笔记·学习·flutter
Xudde.4 小时前
friendly靶机渗透
笔记·学习·安全·web安全·php
0xAaron4 小时前
符号表和 dSYM UUID 确认
ios·cocoa·uuid·符号表·dsym