Ios 在TableView中根据颜色设置UiCell文本颜色

Ios 在TableView中根据颜色设置UiCell文本颜色,ios,swift,uitableview,swiftui,uikit,Ios,Swift,Uitableview,Swiftui,Uikit,我正试图通过UiTableView在屏幕上显示一些日志,我想为那些带有前缀“root”的日志设置红色文本颜色,如下所示: var logList: [String] = [] ... func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.logList.count } func tableVie

我正试图通过
UiTableView
在屏幕上显示一些日志,我想为那些带有前缀“root”的日志设置红色文本颜色,如下所示:

var logList: [String] = []

...

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.logList.count
    }

        
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableview.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! ItemLogCell
        cell.itemLogLabel.text = self.logList[indexPath.row]
        
        print(indexPath.row)
        print(self.logList[indexPath.row].hasPrefix("root"))

        if (self.logList[indexPath.row].hasPrefix("root")) {
            cell.itemLogLabel.textColor = UIColor.red
        }
        
        return cell
    }
问题是,即使前缀条件为false,文本颜色也会变为红色,并且仅适用于某些行


我滚动的次数越多,随机的红色日志就越多。如何解决此问题?

使用不同的
UITableViewDelegate
回调来解决此问题

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    guard let cell = cell as? ItemLogCell else { return }

    print(indexPath.row)
    print(self.logList[indexPath.row].hasPrefix("root"))

    if (self.logList[indexPath.row].hasPrefix("root")) {
        cell.itemLogLabel.textColor = UIColor.red
    }

}

可以执行以下操作重置其他行的颜色:

if (self.logList[indexPath.row].hasPrefix("root")) {
   cell.itemLogLabel.textColor = UIColor.red
}
else {
   cell.itemLogLabel.textColor = UIColor.white
}

因为UITableViewCell基本上是可重用的。假设您看到屏幕上有6个单元格,索引为0到5。当您滚动到索引为6的单元格时,索引为0的单元格将被隐藏。TableView不会为单元格6创建新的UITableViewCell,它会浪费设备的内存。相反,tableview将使单元格0出列并重新使用它。因此,单元格6的默认值为单元格0。要解决此问题,需要重新设置没有前缀“root”的单元格的颜色

解释单元是可重用的,所以你也应该考虑其他情况。矮子

    let cellColor = cell.itemLogLabel.textColor
    self.logList[indexPath.row].hasPrefix("root") ? cellColor = .red : cellColor = .black

该问题是由于退出可重用队列造成的,请尝试使用if条件的其他部分。在UITavleViewCell子类中重写
prepareForReuse()
,并在其中设置默认颜色。在重复使用之前对每个单元调用。
    let cellColor = cell.itemLogLabel.textColor
    self.logList[indexPath.row].hasPrefix("root") ? cellColor = .red : cellColor = .black