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];
}
相关推荐
海尔辛1 小时前
学习黑客抓包wireshark
学习·测试工具·wireshark
Mabnus4 小时前
每周靶点分享:Angptl3、IgE、ADAM9及文献分享:抗体的多样性和特异性以及结构的新见解
学习
原住民的自修室5 小时前
Mac 3大好用的复制粘贴管理工具对比
macos·paste·pastenow·maccy
A_aspectJ7 小时前
【Bootstrap V4系列】学习入门教程之 组件-输入组(Input group)
前端·css·学习·bootstrap·html
Xudde.7 小时前
加速pip下载:永久解决网络慢问题
网络·python·学习·pip
YKPG9 小时前
C++学习-入门到精通-【6】指针
开发语言·c++·学习
Timmer丿9 小时前
kafka学习笔记(四、生产者、消费者(客户端)深入研究(三)——事务详解及代码实例)
java·笔记·学习·kafka
虾球xz9 小时前
游戏引擎学习第269天:清理菜单绘制
c++·学习·游戏引擎
vortex59 小时前
新手上路之 NoSQL 数据库学习
数据库·学习·nosql
MeiYu_12310 小时前
【数据结构与算法】图的基本概念与遍历
数据结构·c++·学习