【问题标题】:Set UiCell text color in TableView according indexPath Swift根据 indexPath Swift 在 TableView 中设置 UiCell 文本颜色
【发布时间】:2021-04-04 01:08:09
【问题描述】:

我正在尝试通过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
    }

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

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

【问题讨论】:

  • 问题是由于出队可重用,请尝试让 if 条件的 else 部分。
  • 在您的 UITavleViewCell 子类中覆盖 prepareForReuse() 并在那里设置默认颜色。在重用每个单元之前都会调用它。

标签: ios swift uitableview swiftui uikit


【解决方案1】:

你可以这样做来重置其他线条的颜色:

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

【讨论】:

    【解决方案2】:

    为此使用不同的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
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      因为 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
      }
      

      【讨论】:

        【解决方案4】:

        由于pham hai 解释单元格是可重复使用的,因此您也应该考虑其他情况。矮个子

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-01-23
          • 2018-02-17
          • 2019-02-12
          • 1970-01-01
          • 2017-06-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多