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];
}
相关推荐
蒸蒸yyyyzwd2 小时前
cpp对象模型学习笔记1.1-2.8
java·笔记·学习
阿蒙Amon3 小时前
TypeScript学习-第7章:泛型(Generic)
javascript·学习·typescript
Hill_HUIL3 小时前
学习日志23-路由高级特性(静态路由)
网络·学习
今儿敲了吗4 小时前
鸿蒙开发第一章学习笔记
笔记·学习·鸿蒙
经年未远7 小时前
vue3中实现耳机和扬声器切换方案
javascript·学习·vue
Hill_HUIL7 小时前
学习日志22-静态路由
网络·学习
詩不诉卿8 小时前
zephyr学习之自定义外部module记录
学习
浮游本尊8 小时前
React 18.x 学习计划 - 第十三天:部署与DevOps实践
学习·react.js·状态模式
wdfk_prog8 小时前
[Linux]学习笔记系列 -- [drivers][dma]dmapool
linux·笔记·学习
电饭叔8 小时前
Tkinter Button 括号内的核心参数详解
python·学习