IOS_SearchBar關鍵字搜索并標注為紅色

如下,實現相關代理方法,

- (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;

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容