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];
}
相关推荐
留白_4 分钟前
【tableau入门学习】6、盒须图、靶心图、四象限图、甘特图、直方图
学习·甘特图
2501_915921436 分钟前
抓包工具对比:Charles、TraceEagle、Wireshark、Fiddler 与 Proxyman
网络协议·计算机网络·网络安全·ios·adb·https·udp
MSTcheng.12 分钟前
【Linux学习】Linux学习第四弹——Linux基本指令3
linux·windows·学习·操作系统·指令
lihaihui199113 分钟前
STM32 学习
学习
是隼人34 分钟前
buuctf-pwn jarvisoj_level5(64位ret2libc)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
9765033351 小时前
iOS 上架/审核 4.3a全面解读-最新
flutter·ios·objective-c·uniapp
2501_915106322 小时前
Flutter iOS混淆打包详细教程与步骤
android·flutter·ios·小程序·uni-app·iphone·webview
DevLoom_3 小时前
MacBook 256GB到底够不够用,日常怎么清理空间?
macos·mac空间清理·mac磁盘空间不足
外域速览6 小时前
OpenAI 智能体「越狱」风波未平,苹果折叠屏 iPhone Ultra 下周三登场
人工智能·ios·iphone
春风解人意10 小时前
从零开始学习嵌入式P32----网络基础之TCP
c语言·网络·学习·tcp/ip