注:将以下方法加到NSString的分类里
/**
* 部分子字符串高亮显示(搜索的内容不进行拆分,直接匹配有则显示)
*
* @param substring 需高亮显示的字符串
* @param color 高亮颜色
*
* @return 富文本字符串
*/
- (NSMutableAttributedString *)stringWithHighLightSubstring:(NSString *)substring highLightColor:(UIColor *)color {
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:self];
NSString * copyTotalString = self;
NSMutableString * replaceString = [NSMutableString stringWithString:@""];
for (int i = 0; i < substring.length; i ++) {
[replaceString appendString:@" "];
}
while ([copyTotalString rangeOfString:substring].location != NSNotFound) {
NSRange range = [copyTotalString rangeOfString:substring];
[attributedString addAttribute:NSForegroundColorAttributeName value:color range:range];
if (copyTotalString.length>range.location) {
copyTotalString = [copyTotalString stringByReplacingCharactersInRange:range withString:replaceString];
}else {
copyTotalString = @"";
}
}
return attributedString;
}
/**
* 部分子字符串高亮显示(支持搜索的内容拆分为单个字符串与整体的数据进行比较)
*
* @param substring 需高亮显示的字符串
* @param color 高亮颜色
*
* @return 富文本字符串
*/
- (NSMutableAttributedString *)stringWithPartHighLightSubstring:(NSString *)substring highLightColor:(UIColor *)color {
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:self];
NSString * copyTotalString = self;
NSMutableString * replaceString = [NSMutableString stringWithString:@" "];
for (int i = 0; i < substring.length; i ++) {
NSString *singleString = [substring substringWithRange:NSMakeRange(i, 1)];
while ([copyTotalString rangeOfString:singleString].location != NSNotFound) {
NSRange range = [copyTotalString rangeOfString:singleString];
//颜色如果统一的话可写在这里,如果颜色根据内容在改变,可把颜色作为参数,调用方法的时候传入
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:range];
copyTotalString = [copyTotalString stringByReplacingCharactersInRange:range withString:replaceString];
}
}
return attributedString;
}
网友评论