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];
}
相关推荐
炎武丶航2 小时前
汽车功能测试学习(1):FCW前方碰撞预警
功能测试·学习·汽车
zhao1zhihui7 小时前
iOS Bug 定位实战:从断点、LLDB 到 Xcode 与 Instruments
ios·xcode
qq_185198698 小时前
SpingBoot3入门学习一
学习
噗噗夹的TA之旅8 小时前
Shader 学习 21:自定义 Render Feature
学习·游戏·unity·c#·游戏引擎·图形渲染
zhao1zhihui8 小时前
Objective-C Runtime:从消息派发到安全 Hook
ios
码农小韩9 小时前
AIAgent应用开发——大模型理论基础与应用(七)
python·学习·ai·大模型·agent
寒水馨9 小时前
macOS下载、安装PowerShell-v7.6.4(附安装包powershell-7.6.4-osx-arm64.pkg)
macos·自动化·跨平台·shell·脚本·命令行·powershell
流云鹤10 小时前
05Java学习day(5)
java·学习
only-lucky10 小时前
QML深入学习五(Controls模块)
前端·javascript·学习
GitLqr10 小时前
Flutter FocusNode 实战指南:玩转键盘焦点与用户输入体验
android·flutter·ios