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];
}
相关推荐
UIU1146 小时前
递归算法与汉诺塔
c++·学习·算法·c#·递归
茶底世界之下11 小时前
导出进度不是一个百分比:AVFoundation 收尾阶段的状态建模
ios·swift
用户21816970493011 小时前
FFmpeg (二) shell echo 数组
objective-c
大熊猫侯佩11 小时前
macOS27 上可变界面尺寸 iOS App 揭秘
macos·ios·swiftui
tangzzzfan11 小时前
把 ADB 装进 macOS app
macos
大熊猫侯佩11 小时前
iPhone Duo 从外屏到内屏:ArrangementView 抢先适配
swiftui·xcode·apple
用户21816970493011 小时前
LLVM
ios
大熊猫侯佩11 小时前
为 iPhone Duo 做准备:containerConcentric 自适配指南
前端·swiftui·xcode
zeqinjie11 小时前
Flutter 获取 iPhone Duo 预留区位置
前端·flutter·ios
二流小码农11 小时前
鸿蒙开发:ArrayList,可不会让UI更新哦
android·ios·harmonyos