摘要:实现对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