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];
}
相关推荐
Thexhy1 小时前
在 CentOS 7 的 Linux 系统中配置 NFS
linux·运维·学习·centos
CodeLongBear2 小时前
计算机网络学习笔记 | 传输层核心知识点总结(DAY03,匠心制作)
笔记·学习·计算机网络
晓北斗NorSnow2 小时前
机器学习核心算法与学习资源解析
学习·算法·机器学习
wdfk_prog3 小时前
[Linux]学习笔记系列 -- [kernel][time]tick
linux·笔记·学习
我命由我123454 小时前
Photoshop - Photoshop 工具栏(22)单行选框工具
学习·ui·职场和发展·求职招聘·职场发展·学习方法·photoshop
User_芊芊君子5 小时前
【成长纪实】我的鸿蒙成长之路:从“小白”到独立开发,带你走进鸿蒙的世界
学习·华为·harmonyos·鸿蒙开发
QuantumLeap丶6 小时前
《Flutter全栈开发实战指南:从零到高级》- 09 -常用UI组件库实战
flutter·ios·dart
嵌入式-老费7 小时前
自己动手写深度学习框架(快速学习python和关联库)
开发语言·python·学习
执笔论英雄7 小时前
【大模型训练】zero 学习及deepseed实战
人工智能·深度学习·学习
淡忘_cx7 小时前
Dify 插件开发与打包教程 (Mac)
macos