iOS - 搜索关键字在结果中高亮显示

 

self.labelContent.attributedText = [self highlightText:self.searchStr inStr:searchModel.eventDesc];

- (NSAttributedString *)highlightText:(NSString *)keyword inStr:(NSString *)str {
    NSRange range = [str rangeOfString:keyword];
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:str];
    if (range.length > 0) {
        [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    } else {
    }
    return [[NSAttributedString alloc]initWithAttributedString:attrStr];
}

 

 

- (NSAttributedString *)highlightText:(NSString *)keyword inStr:(NSString *)str {
    NSRange range = [str rangeOfString:keyword];
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:str];
    if (range.length > 0) {
        [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
        
    } else {
        
    }
    
    return [[NSAttributedString alloc]initWithAttributedString:attrStr];
}


#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *str = [self.strs objectAtIndex:indexPath.row];
    cell.textLabel.attributedText = [self highlightText:self.searchTextField.text inStr:str];
}

 

posted @ 2019-06-25 18:15  公羽寒  阅读(794)  评论(0编辑  收藏  举报