给UIlabel的内容中的特定字符添加颜色,可以调整大小


摘要:实现对NSAttributedString的一个扩展,用法见.m的注释内容


#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>


@interface NSAttributedString (color)


+ (instancetype)getAtriWith:(NSString*)markup withDestStr:(NSArray*)deStrs andColor:(NSArray*)colors andFont:(NSArray*)fonts;


@end



#import "NSAttributedString+color.h"


@implementation NSAttributedString (color)


+ (instancetype)getAtriWith:(NSString*)markup withDestStr:(NSArray*)deStrs andColor:(NSArray*)colors andFont:(NSArray*)fonts{

    

    NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:markup];

    int count = 0;

    for (NSString* str in deStrs){

        NSRegularExpression *regex = [[NSRegularExpression alloc]initWithPattern:str options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:nil];//2

        NSArray *chunks = [regex matchesInString:markup options:0 range:NSMakeRange(0, [markup length])];

        

        int subCount = 0;

        if (chunks.count > 1 && count > 0){

            subCount = count;

        }

        

        int tag = 0;

        for (NSTextCheckingResult *b in chunks) {

            [aString addAttribute:NSForegroundColorAttributeName value:colors[count] range:b.range];

            [aString addAttribute:NSFontAttributeName value:fonts[count] range:b.range];

            

            if (tag == subCount){

                break;

            }

            tag++;

        }

        count++;

    }

    

    return aString;

}


/**

  UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, 300, 0)];

 label.numberOfLines = 0;

 NSString *mark = @" 的天 小桥 流水 am id text core last 即使对方空间哈上课大家互粉阿萨德发阿萨德空间凤凰ask ";

 NSArray *destrs = @[@"",@"流水"];

 NSArray *fonts = @[[UIFont systemFontOfSize:18],[UIFont systemFontOfSize:21]];

 NSArray *colors = @[[UIColor redColor],[UIColor greenColor]];

 NSAttributedString *str = [NSAttributedString getAtriWith:mark withDestStr:destrs andColor:colors andFont:fonts];

 label.attributedText = str;

 [label sizeToFit];

 [self.view addSubview:label];

 */


@end



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值