【发布时间】: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