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];
}
相关推荐
路灯上の马陈36 分钟前
Java 内部类 学习笔记
笔记·学习
前进的李工1 小时前
Agent 学习笔记 12:Agent 的工具应该怎么设计
人工智能·笔记·学习·agent·工具调用·skill·工具设计
li星野1 小时前
从 DICOM 到声学属性学习记录:HU 值怎么变成密度和声速
学习
自信150413057592 小时前
重生之从0开始学习c++之——vector-中篇
c++·学习·算法
架构师伯子明2 小时前
ffmpeg学习4:opencv在音视频领域常用指令
opencv·学习·ffmpeg
独隅2 小时前
WebStorm macOS 安装部署与高效调优完全指南
ide·macos·webstorm
独隅13 小时前
WebStorm macOS 安装调优与实战效能全景
ide·macos·webstorm
wangqiaowq14 小时前
Ontology 学习
学习
2601_9679873715 小时前
安装 Redis 或 Redis Stack
linux·windows·redis·macos·安装
choumou_M16 小时前
算法_1:由浅入深学习快速排序QuickSort
学习·算法·排序算法