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];
}
相关推荐
sharemylove7 小时前
Java学习笔记 —— 面向对象专题
java·开发语言·笔记·学习·课程设计
代码民工正电荷8 小时前
JAVA学习基础(一)
java·开发语言·学习
AvocadoZeroOneOI12 小时前
Kadane 算法(最大子段和)
c++·学习·算法·动态规划
传奇开心果编程14 小时前
【六大移动UI框架比较学与练】第3课:文本、图片、布局核心组件实战对照
android·flutter·react native·ios·swiftui·移动开发·android jetpack
FungLeo15 小时前
Swift macOS 游戏开发实战|空当接龙 07|使用 Swift 计算稳定牌桌布局与命中区域
macos·swift·游戏开发·界面布局·命中检测
FungLeo16 小时前
Swift macOS 游戏开发实战|空当接龙 06|使用 SVG 与 Node.js 制作 macOS 游戏牌面
macos·node.js·svg·swift·游戏素材
艾欧饲18 小时前
能力、Entitlement 与扩展:侧载的 App 为什么装上了,有的功能却不能用
ios
楚山之石18 小时前
扩散时间 Δ 与脉宽 δ——TE 缩短如何提高 b 值 SNR
图像处理·学习·mri·医学影像
庚鑫18 小时前
只改最低支持版本,为什么 iOS 播放器在初始化时崩了?
ios
黑科技iOS上架19 小时前
机审友好的iOS混淆方案:无固定二进制特征才能过审4.3
flutter·ios·objective-c·cocoa·审核