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];
}
相关推荐
坤坤子吖23 分钟前
C++继承:继承的基本用法与访问规则
开发语言·c++·笔记·学习
加载力科技36 分钟前
Mac解压RAR分卷全攻略-part01part02一键合并
macos·mac 解压 rar 分卷·rar 分卷·part01·mac 解压工具·乐压·分卷合并
茶底世界之下1 小时前
方图一定要裁照片吗?用 Awaking 比较裁切与留白
ios
代码山河1 小时前
键盘输入与输出:Scanner与System.out详解
java·学习·架构·教程·面向对象·项目
一楼的猫1 小时前
活动会议照片直播云相册:服务形式与适用场景
学习
愤怒火龙果1 小时前
AIGC 安全学习笔记02 后门攻击・LLM 安全靶场・提示词注入
学习·安全·aigc
kkkkkkkkkk_Z1 小时前
新手自学嵌入式 | 学习日记: Linux驱动进阶 —— Platform总线与I2C子系统实战
linux·运维·学习
外收内放1 小时前
FastAPI猜字谜实战(3):把每一局存成JSON
开发语言·python·学习·json·fastapi
Yurko132 小时前
原码、反码、补码的快速学习
笔记·学习·其他
2601_967979123 小时前
Opteryx Python库 macOS版本0.0.0a12
python·macos·1024程序员节·wheel·opteryx·alpha