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];
}
相关推荐
游戏开发爱好者89 小时前
TraceEagle 代理抓包详解,无感代理、去证书绑定与 HTTP/3 解密能力解析
网络协议·计算机网络·网络安全·ios·adb·https·udp
编程圈子10 小时前
电机驱动开发学习21. R3_2 双相扇区电流采样与第三相重构
驱动开发·学习·重构
aiopencode10 小时前
SwiftUI Introspect生产环境完全指南:为什么它是安全可靠的选择
后端·ios
听雨入夜10 小时前
CMake构建学习笔记-libxml库的构建
笔记·学习
for_ever_love__11 小时前
iOS: 网络管理单例
学习·ios·objective-c
不在逃避q11 小时前
一步一步学习使用LiveBindings()TListView进阶使用(),打造天气预报程序
服务器·数据库·学习
00后程序员张12 小时前
iOS加固技术路线全面解析:Bitcode模式、源码模式与汇编模式对比及爱加密优势
android·汇编·ios·小程序·uni-app·cocoa·iphone
知识分享小能手12 小时前
高等数学学习教程,从入门到精通,微分中值定理与导数的应用(5)
学习·机器学习·概率论
520拼好饭被践踏12 小时前
JAVA+Agent学习day25
java·开发语言·学习
起司喵喵12 小时前
Flutter-MacOS桌面OS系统|flutter.+window_manager客户端OS模板
flutter·macos·策略模式