UITableView中突出显示和取消突出显示的文本

问题描述 投票:0回答:1

我想突出显示和取消突出显示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文本?

swift uitableview nsattributedstring
1个回答
0
投票

在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。

© www.soinside.com 2019 - 2024. All rights reserved.