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 小时前
JS数组不止Array!索引集合类全面解析
开发语言·前端·javascript·学习·js
冬夜戏雪2 小时前
【java学习日记】【2025.12.7】【7/60】
java·开发语言·学习
sweet丶3 小时前
理解iOS中Protobuf:一个比JSON更好,但不是替代
ios·性能优化·架构
wubba lubba dub dub7503 小时前
第二十八周 学习周报
学习
思成不止于此3 小时前
MySQL 查询实战(三):排序与综合练习
数据库·笔记·学习·mysql
QiZhang | UESTC3 小时前
学习日记day42
学习
深海潜水员4 小时前
OpenGL 学习笔记 第一章:绘制一个窗口
c++·笔记·学习·图形渲染·opengl
大、男人5 小时前
DeepAgent学习
人工智能·学习
测试人社区—66795 小时前
提升测试覆盖率的有效手段剖析
人工智能·学习·flutter·ui·自动化·测试覆盖率
崇山峻岭之间5 小时前
C++ Prime Plus 学习笔记026
c++·笔记·学习