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];
}
相关推荐
别动我齐刘海14 小时前
Day6 unitree_G1人形机器人GMR—— MotionInput
c语言·c++·人工智能·学习·机器学习·机器人·github
zzzll111116 小时前
0基础入门大模型:一份清晰的学习路线图
人工智能·学习·chatgpt
正经人_x16 小时前
学习日记48:DenseCLIP
学习
DevangLic17 小时前
monkeycode-使用说明
学习·ai
red_redemption18 小时前
自由学习记录(211)
学习
赶路人儿18 小时前
MacOS 下实现 AI 操控电脑(Computer Use)的思考
人工智能·macos·策略模式
ThsPool19 小时前
【ENVI二次开发学习整理 02】IDL语言基础与程序设计
学习·中间件
AIsoft_868819 小时前
iPhone录音重点标记:会议录音与重点内容同步保存功能实测
ios·iphone
00后程序员张19 小时前
使用Instruments工具深入分析iOS应用性能与启动时间优化
android·macos·ios·小程序·uni-app·cocoa·iphone
一只小菜鸡..19 小时前
南京大学 操作系统 (JYY) 学习笔记:文件系统实现——从 FAT、ext2 到现代 B-Tree 黑科技
笔记·科技·学习