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];
}
相关推荐
学编程的闹钟3 小时前
PHP变量类型转换机制全解析
学习
AI360labs_atyun6 小时前
字节AI双王炸来了!Seedance 2.0 + Seedream 5.0
人工智能·科技·学习·百度·ai
不用89k7 小时前
SpringBoot学习新手项初识请求
java·spring boot·学习
汐汐咯7 小时前
CNN学习
深度学习·学习·cnn
rock——you7 小时前
macos如何升级到指定版本,而不是默认最新的版本。我的现在为15.3,如何升级到15.4,而不是最新的15.54
macos
打倒苦瓜蛋7 小时前
Mac typora安装 破解教程!!!
macos
蓝胖子Lcl7 小时前
Mac安装Oracle数据库(M芯片)
数据库·macos·oracle
shadow fish7 小时前
react学习记录(三)
javascript·学习·react.js
Aliex_git8 小时前
浏览器 API 兼容性解决方案
前端·笔记·学习
四谎真好看8 小时前
SSM学习笔记(Spring篇 Day02)
笔记·学习·学习笔记·ssm