微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

根据 indexPath Swift

如何解决根据 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?