根据 indexPath Swift

问题描述

我正在尝试通过 UiTableView 在屏幕上显示一些日志,并且我想为那些 hasPrefix "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
    }

问题是即使前缀条件为假,文本颜色也会变成红色,并且仅针对某些行。

我滚动得越多,随机的红色日志就越多。我该如何解决这个问题?

解决方法

为此使用不同的 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”的单元格的颜色

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

正如 pham hai 解释单元格是可重用的,所以您也应该考虑其他情况。矮个

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...