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];
}
相关推荐
CHB3 小时前
uni-app x 蒸汽模式 性能测试基准报告 Benchmark【Android版】
android·ios·uni-app
圆奋奋4 小时前
FreeRTOS学习(三)- 任务调度模块
学习·开源·freertos
吃着火锅x唱着歌5 小时前
Effective C++ 学习笔记 条款40 明智而审慎地使用多重继承
c++·笔记·学习
Magic-ZYJ5 小时前
不登录、不联网也能用:我是如何设计一款“本地优先”iOS App 的
ios·app·iphone·研发·独立开发者·心情日记
xian_wwq5 小时前
【学习笔记】Prompt Engineering 没死,只是它不再够用了-2/16
笔记·学习·prompt
天吾cc6 小时前
RTT-ADC
单片机·嵌入式硬件·学习
kaixin_啊啊6 小时前
test_机器学习算法学习
学习·算法·机器学习
_阿南_6 小时前
flutter 展示的字体突然奔放了
android·flutter·ios
m4Rk_6 小时前
【论文阅读】Agent 记忆机制(34):MemoryBank——用遗忘曲线管理可强化的长期对话记忆
论文阅读·人工智能·学习·开源·github
凤山老林6 小时前
在 Apple 芯片的 Mac 上通过 VMware Fusion 使用 Windows 11
windows·macos·vmware·虚拟机