我们在使用Google进行搜索时会看到搜索的关键字高亮的效果:
iOS客户端字符串中子字符串实现的代码:
+(NSMutableAttributedString *)stringWithHighLightSubstring:(NSString *)totalString substring:(NSString *)substring{
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:totalString];
NSString * copyTotalString = totalString;
NSMutableString * replaceString = [NSMutableString stringWithCapacity:0];
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;
}
可以将该方法写在NSMutableAttributedString的分类中,用NSMutableAttributedString直接调用。
调用示例代码:
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, self.view.frame.size.width - 40, 80)];
label.attributedText = [NSMutableAttributedString stringWithHighLightSubstring:@"给岁月以文明,而不是给文明以岁月!" substring:@"文明"];
[self.view addSubview:label];
效果展示: