/**
改变UILabel部分字符颜色
*/
- (void)setContentLabelColor {
NSString *content = @"2018-08-27\n写博客\n2018-08-27\n写博客\n2018-08-27\n写博客\n2018-08-27\n写博客\n2018-08-27\n写博客\n2018-08-27\n写博客\n2018-08-27\n写博客\n2018-08-27\n写博客";
NSMutableArray *locationArr = [self calculateSubStringCount:content str:@"\n"];
NSMutableAttributedString *attstr = [[NSMutableAttributedString alloc] initWithString:content];
for (int i=0; i<locationArr.count; i++) {
if (i%2==0) {
NSNumber *location = locationArr[i];
[attstr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:255.0f/255.0f green:45.0f/255.0f blue:81.0f/255.0f alpha:1.0f] range:NSMakeRange(location.integerValue-10, 10)];//改变\n前边的10位字符颜色,
}
}
self.contentLabel.attributedText = attstr;
}
/**
查找子字符串在父字符串中的所有位置
@param content 父字符串
@param tab 子字符串
@return 返回位置数组
*/
- (NSMutableArray*)calculateSubStringCount:(NSString *)content str:(NSString *)tab {
int location = 0;
NSMutableArray *locationArr = [NSMutableArray new];
NSRange range = [content rangeOfString:tab];
if (range.location == NSNotFound){
return locationArr;
}
//声明一个临时字符串,记录截取之后的字符串
NSString * subStr = content;
while (range.location != NSNotFound) {
if (location == 0) {
location += range.location;
} else {
location += range.location + tab.length;
}
//记录位置
NSNumber *number = [NSNumber numberWithUnsignedInteger:location];
[locationArr addObject:number];
//每次记录之后,把找到的字串截取掉
subStr = [subStr substringFromIndex:range.location + range.length];
NSLog(@"subStr %@",subStr);
range = [subStr rangeOfString:tab];
NSLog(@"rang %@",NSStringFromRange(range));
}
return locationArr;
}
摘自:https://blog.csdn.net/feiyue0823/article/details/82114430