在开发过程中总会遇到改变字符串中一些字的颜色,就是简单而不常用,都会使用,但每次写都会觉得比较麻烦,索性就给NSString增加一个类方法,每次使用直接调用就行。代码如下:
.h
NS_ASSUME_NONNULL_BEGIN
@interfaceNSString (ChangeColorCharacter)
/*
*originalString 原始字符串
*changeColorCharArr 原始字符串中需要改变的字符的数组
*targetColor 要改变的颜色
*/
+(NSMutableAttributedString*)changeColorCharWithOriginalString:(NSString*)originalString needChangCorolCharArr:(NSArray*)changeColorCharArr targetColor:(UIColor*)targetColor;
@end
NS_ASSUME_NONNULL_END
.m
@implementationNSString (ChangeColorCharacter)
+(NSMutableAttributedString*)changeColorCharWithOriginalString:(NSString*)originalString needChangCorolCharArr:(NSArray*)changeColorCharArr targetColor:(UIColor*)targetColor{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:originalString];
for(NSString*searchStrinchangeColorCharArr) {
NSError*error =NULL;
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:searchStr options:NSRegularExpressionIgnoreMetacharacters error:&error];
NSArray*rangeArray = [expressionmatchesInString:originalStringoptions:0range:NSMakeRange(0, originalString.length)];
for(NSTextCheckingResult*resultinrangeArray) {
NSRangerange = [resultrange];
if(range.location!=NSNotFound) {
[attributedStringaddAttribute:NSForegroundColorAttributeNamevalue:targetColorrange:NSMakeRange(range.location,range.length)];
}
}
}
returnattributedString;
}
@end