美文网首页
IOS_SearchBar关键字搜索并标注为红色

IOS_SearchBar关键字搜索并标注为红色

作者: 无法触碰 | 来源:发表于2016-12-08 09:27 被阅读205次

如下,实现相关代理方法,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];

// 显示搜索结果时

if (self.searchController.active) {

// 原始搜索结果字符串.

NSString *originResult = self.arrOfSeachResults[indexPath.row];

// 获取关键字的位置

NSRange range = [originResult rangeOfString:self.searchController.searchBar.text];

// 转换成可以操作的字符串类型.

NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:originResult];

// 添加属性(粗体)

[attribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:range];

// 关键字高亮

[attribute addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];

// 将带属性的字符串添加到cell.textLabel上.

[cell.textLabel setAttributedText:attribute];

cell.textLabel.text = self.arrOfSeachResults[indexPath.row];

} else {

cell.textLabel.text = self.arrOfSeachBoxes[indexPath.row];

}

return cell;

}

相关文章

网友评论

      本文标题:IOS_SearchBar关键字搜索并标注为红色

      本文链接:https://www.haomeiwen.com/subject/zrnjmttx.html