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_1 分钟前
【论文阅读】Agent 记忆机制(49):MemCoE——先学习如何组织记忆,再学习具体记住什么
论文阅读·人工智能·学习·开源·github
我爱cope12 分钟前
【计算机网络 | 网络层4:子网掩码与 CIDR:如何判断网络号和主机号?】
网络·学习·计算机网络
MSTcheng.23 分钟前
【Linux学习】Linux学习第二弹——Linux基本指令1
linux·运维·服务器·学习·指令
2501_9159184123 分钟前
Rust 程序抓包解密,rustls 不认系统证书的几种办法
开发语言·后端·网络协议·ios·adb·https·rust
guoguoshizhuo26 分钟前
mac电脑免费使用Typora教程
macos
MaoJiu27 分钟前
「Landmark-Driven Beauty Rendering:实时磨皮与腮红的算法与 GPU 实现」
ios
05664638 分钟前
python高级——Python 类型提示与 Pydantic
网络·人工智能·windows·python·学习
M78佐菲42 分钟前
Linux学习笔记:目录IO与帧缓冲
linux·笔记·学习·算法
其实防守也摸鱼1 小时前
如何使用自动化教育SRC漏洞挖掘系统--AutoHunter
运维·网络·人工智能·学习·安全·web安全·自动化
智脑API1 小时前
CCSwitch 在 macOS 上怎么接入 Codex?安装、API 配置与权限设置教程
macos