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];
}
相关推荐
Go-higher14 小时前
DriverTest 驾考知识卡片学习助手 —— 一款基于 Jetpack Compose 的现代 Android 学习APP
android·学习
星幻元宇VR14 小时前
公共安全主题展厅设备【防洪防汛安全科普系统】
科技·学习·安全
AI科技星15 小时前
32维超复数流形中意识信息场与物质耦合的拓扑动力学
人工智能·学习·算法·数据挖掘·回归·乖乖数学·全域数学
鱼很腾apoc15 小时前
【Linux】第7期 进程间通信 (IPC) 详解:管道 (匿名 / 命名) + System V
linux·服务器·c语言·学习·进程间通信·ipc
科技大视界16 小时前
大学生专业课笔记本用哪款?来酷Air14酷睿版14英寸轻薄笔记本电脑适合学习任务多的人
学习
国服第二切图仔16 小时前
HarmonyOS APP《画伴梦工厂》开发第31篇-语音识别实战——SpeechRecognitionEngine+AudioCapturer
语音识别·xcode·harmonyos
weixin_4235339916 小时前
c++类的继承学习-去中心化交易所(DEX)的“流动性池初始化与交易指令”设计
c++·学习·去中心化
远离UE417 小时前
UE5 各类型灯光学习
学习·ue5
New农民工17 小时前
射频芯片学习-dBm概念
学习·射频学习
唐诺18 小时前
Objective-C 之 Category 详解
objective-c·category