ios - 根据 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
}
问题是即使前缀条件为假,文本颜色也会变为红色,并且仅适用于某些行。
我滚动得越多,随机的红色日志就越多。我怎样才能解决这个问题 ?
解决方案
为此使用不同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
}
}
推荐阅读
- amazon-web-services - AWS Elastic Beanstalk 通过 .ebextensions 设置根卷
- makefile - 在不同的目录中创建相同的工作流程
- html - Chrome 和输入日期
- r - 在 R 中计算 rowNorms 的更有效方法?
- python - Python pandas to_sql 违反外键约束
- mysql - 需要验证我的 SQL 查询是否正确
- python - 如何将python中的输出保存到.txt文件
- python - 无法使用 Pyspark 写入数据文件?
- c# - C# SetValues,EntityState.Modified 不起作用
- google-sheets - ArrayFormula、SumProduct 和 Google 表格仅返回 1 个值