我想突出显示和取消突出显示UITableView
中的搜索文本。
为了突出显示搜索到的文本,我尝试了以下CellForRow
中的代码,并且突出显示了搜索到的文本很好用。
let range = (self.modelClass.users[indexPath.row].name as NSString).range(of: self.searchBar.text!, options: .caseInsensitive)
let attributedString = NSMutableAttributedString(string: self.modelClass.users[indexPath.row].name)
attributedString.addAttributes([NSAttributedString.Key.backgroundColor: Colors.highlightedColor, NSAttributedString.Key.font: cell.lblName.font], range: range)
cell.lblName.attributedText = attributedString
编辑1
if searchBar.text != "" {
let range = (self.modelClass.users[indexPath.row].name as NSString).range(of: self.searchBar.text!, options: .caseInsensitive)
let attributedString = NSMutableAttributedString(string: self.modelClass.users[indexPath.row].name)
attributedString.addAttributes([NSAttributedString.Key.backgroundColor: Colors.highlightedColor, NSAttributedString.Key.font: cell.lblName.font], range: range)
cell.lblName.attributedText = attributedString
}
else {
cell.lblName.text = self.modelClass.users[indexPath.row].name
}
但是当我清除搜索的数据并加载默认数组但在lblName
UILabel
中没有清除突出显示的颜色时。
请指导我如何取消突出显示UILabel
文本?
在cellForRowAt中,您还需要为默认标签视图传递else条件。
if self.searchBar.text != "" {
let range = (self.modelClass.users[indexPath.row].name as NSString).range(of:
self.searchBar.text!, options: .caseInsensitive)
let attributedString = NSMutableAttributedString(string:
self.modelClass.users[indexPath.row].name)
attributedString.addAttributes([NSAttributedString.Key.backgroundColor:
Colors.highlightedColor, NSAttributedString.Key.font: cell.lblName.font], range: range)
cell.lblName.attributedText = attributedString }
else {
// your default label text and color
}
当searchBar文本更改时重新加载TableView。