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];
}
相关推荐
2301_802651089 分钟前
linux系统的学习:网络
linux·网络·学习
2501_9160088910 分钟前
Flutter 开发 iOS,项目打包成 IPA,命令与免 Xcode两种方法
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
zyf10441620 分钟前
暑期实践日志 Day44:梳理剪辑实践成果,进行学习总结
学习·计算机网络·剪辑·暑期实践·课题任务
ouynagda20 分钟前
Linux Socket 网络编程学习笔记
linux·网络·学习
我爱cope29 分钟前
【计算机网络 | 网络层12:SDN:控制平面与数据平面分离意味着什么?】
网络·学习·计算机网络·平面
优化Henry40 分钟前
5G网络切片之S-NSSAIlist相关参数解析
运维·服务器·网络·笔记·学习·信息与通信
tju新生代魔迷1 小时前
Verilog HDL学习笔记(六)| 第6章 数据流建模
笔记·学习
凯尔萨厮1 小时前
Java学习笔记十二(异常与IO)
笔记·学习
冬夜戏雪2 小时前
学习日记-LRU缓存成员变量,入参day1
学习