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];
}
相关推荐
Bernice橘子2 小时前
职场英语学习计划Day034
学习
2501_915909062 小时前
全面解析iOS应用上架到App Store的完整流程与关键注意事项
android·macos·ios·小程序·uni-app·cocoa·iphone
磊灬泽3 小时前
【从零学习 MQTT】发布/订阅、主题、QoS 与报文解析
学习
0566463 小时前
Python数据结构——循环队列
python·学习
00后程序员张3 小时前
抓包鹰 电脑本机网络连接表怎么看?哪些程序在联网 进程归属与可疑 IP 追溯
网络协议·计算机网络·网络安全·ios·adb·https·udp
天国梦3 小时前
2026高中生英语词汇学习APP测评:天学网等4款产品实测对比
学习
我爱cope4 小时前
【计算机网络 | 物理层3:数字编码与调制:比特如何变成可传输的信号?】
网络·学习·计算机网络
一只小菜鸡..4 小时前
南京大学 操作系统 (JYY) 学习笔记:最终章——操作系统的宇宙,与我们的星辰大海
笔记·学习
2501_915918415 小时前
免 Xcode 开发 iOS,工具链替代方案与编译、签名、安装
ide·vscode·macos·ios·个人开发·xcode·敏捷流程
初级代码游戏7 小时前
iOS开发 Swift 速记5:高级运算符
ios·移动开发·swift