- 支持搜索的内容拆分为单个字符串与整体的数据进行比较
- (NSMutableAttributedString *)stringWithHighLightSubstring:(NSString *)totalString substring:(NSString *)substring{
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:totalString];
NSString * copyTotalString = totalString;
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;
}
E5D4FAB8-FBCB-45AB-AF74-A2CE938F1FEB.png
- 搜索的内容不进行拆分,直接匹配有则显示
- (NSMutableAttributedString *)stringWithHighLightSubstring:(NSString *)totalString substring:(NSString *)substring{
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:totalString];
NSString * copyTotalString = totalString;
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:[UIColor orangeColor] range:range];
copyTotalString = [copyTotalString stringByReplacingCharactersInRange:range withString:replaceString];
}
return attributedString;
}
A262F7A9-DA1F-4351-B8C5-0CD4A99143B6.png
网友评论