//cellforrow方法中
if (self.searchController.active) {
self.selectForwardCell.selectForwardModel = self.searchList[indexPath.row];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.selectForwardCell.selectForwardModel.name];
UIColor *highlightedColor = [UIColor colorWithRed:0 green:131/255.0 blue:0 alpha:1.0];
NSArray *strArr = [self rangeOfSubString:self.searchString inString:self.selectForwardCell.selectForwardModel.name];
for (NSValue *value in strArr) {
NSRange range = [value rangeValue];
[attributedString addAttribute:NSForegroundColorAttributeName value:highlightedColor range:range];
}
self.selectForwardCell.titleLable.attributedText = attributedString;
}else{
self.selectForwardCell.selectForwardModel = self.dataSource[indexPath.row];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.selectForwardCell.selectForwardModel.name];
self.selectForwardCell.titleLable.attributedText = attributedString;
}
//循环查找相似的搜索关键字
- (NSArray*)rangeOfSubString:(NSString*)subStr inString:(NSString*)string {
NSMutableArray *rangeArray = [NSMutableArray array];
NSString*string1 = [string stringByAppendingString:subStr];
NSString *temp;
for(int i =0; i < string.length; i ++) {
temp = [string1 substringWithRange:NSMakeRange(i, subStr.length)];
if ([temp isEqualToString:subStr]) {
NSRange range = {i,subStr.length};
[rangeArray addObject: [NSValue valueWithRange:range]];
}
}
return rangeArray;
}