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 小时前
AI Agent Skills实战教程:从原理到上手编写SKILL.md
人工智能·深度学习·学习·机器学习
FairGuard手游加固2 小时前
iOS 游戏加固技术解析:代码混淆、资源加密、内存保护与重签名检测
安全·游戏·macos·unity·ios·objective-c
春风解人意2 小时前
从零开始学习嵌入式P29----线程间的通信
c语言·嵌入式硬件·学习
kmomo..2 小时前
Linux 进程学习笔记
linux·笔记·学习
白猫不黑2 小时前
运维如何转安全(个人经验篇)
运维·学习·安全·web安全·网络安全·信息安全
思盛iOS签名上架3 小时前
iOS企业签名原理是什么?
macos·ios·cocoa
kyrie_sakura3 小时前
python学习笔记 7--- 文件(IO)操作
笔记·python·学习
xiaoxiangsiyan3 小时前
网络智能化转型核心模块全解析
运维·服务器·网络·数据库·学习·架构·php
minglie14 小时前
espidf的iic波特律动oled
学习
Daniel_Coder4 小时前
我用 SwiftUI + GRDB 做了一个「按时吃药·服药提醒」App
ios·swiftui·swift·widgetkit