首页 > 解决方案 > 根据 indexPath Swift 在 TableView 中设置 UiCell 文本颜色

问题描述

我正在尝试在屏幕上显示一些日志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
    }

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

我滚动得越多,随机的红色日志就越多。我怎样才能解决这个问题 ?

标签: iosswiftuitableviewswiftuiuikit

解决方案


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

}

推荐阅读