如何解决根据 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 举报,一经查实,本站将立刻删除。