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];
}
相关推荐
坏柠12 小时前
从一个设备控制面板开始,系统学习 LVGL 界面开发
android·javascript·学习
创业之路&下一个五年12 小时前
委托、事件、发布-订阅模式全梳理(完整总结)
学习·总结
鸠摩智首席音效师12 小时前
如何在 macOS 上安装 .NET Core ?
macos·.netcore
MartinYeung512 小时前
[论文学习] 全同态加密下的加密文字比较与子字串搜寻演算法延伸研究
学习·区块链·同态加密
Front思12 小时前
如何学习Shopify前端开发?
前端·学习
再玩一会儿看代码13 小时前
Java浅拷贝和深拷贝理解笔记
java·linux·开发语言·笔记·python·学习
我命由我1234513 小时前
Excel - Excel 查看当前单元格格式
运维·学习·职场和发展·excel·求职招聘·职场发展·学习方法
花落yu13 小时前
AI学习:第4天
学习
壹号用户13 小时前
缺省参数和函数重载
c++·学习
MartinYeung513 小时前
[论文学习]利用自学习激活函数强化全同态加密下的隐私保护机器学习
学习·机器学习·同态加密