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];
}
相关推荐
Z21-X1 小时前
云原生运维学习笔记:Kubernetes Volume 与 Secret 实验
运维·笔记·学习·云原生·kubernetes
console.log('npc')5 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
茶底世界之下5 小时前
洗衣房的午后斜光:用 Awaking 把光和影分开
ios·app·产品
星落梦生8 小时前
Docker学习(11)
学习·docker·容器
我是谁的程序员1 天前
iOS 性能分析在 Windows 上怎么做,用 KXBuild 的 kxdevice 替代 Instruments
后端·ios
开心就好20251 天前
通配符 Bundle ID 和精确 Bundle ID 怎么选,推送、iCloud 能不能用通配符
后端·ios
布莱克6051 天前
Swift 枚举详解:从基础语法到关联值与模式匹配
开发语言·ios·swift·枚举
茶底世界之下1 天前
冬日窗边的早餐:用 Awaking 留住冷光里的暖意
ios·app·产品
布莱克6051 天前
Swift 闭包详解:从语法到实战的完整指南
服务器·开发语言·ios·ssh·swift·闭包