具有动态backgroundColor的Xcode静态单元格

时间:2018-09-25 17:56:42

标签: swift xcode uitableview

是否可以在UITableView中使用静态单元格设置动态backgroundColor?

例如,用户按下UITableView中的按钮,然后同一视图中的所有单元格都变为特定的颜色。

我已经想出了显示视图时如何设置backgroundColor的方法:

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cell.backgroundColor = UIColor.black
}

现在,我想在视图已加载时实现相同的效果。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

您可以通过visibleCells属性访问当前可见的单元格(经过willDisplay里程碑的那些单元格)。您可以遍历此数组并执行所需的任何操作:

for cell in tableView.visibleCells {
    cell.backgroundColor = UIColor.black
}

或者,您可以在tableView上调用reloadData(),这将导致重新创建并重新显示所有单元格。

答案 1 :(得分:0)

您可以使用一种名为DidSelect的委托方法,当用户在tableView或某个元素内点击一个单元格并返回所选单元格的索引路径时,该方法就可以使用该方法来编辑背景色或任何东西。 该函数内部的代码应为optional func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)类似的代码,您可以使用cellForRowAtIndexPath获取单元格,并将其传递给选定的路径,并将其强制转换为您拥有的单元格类型,然后对其进行编辑或执行任何操作。

完整代码如下所示

optional func tableView(_ tableView: UITableView, 
         didSelectRowAt indexPath: IndexPath){
let cell = tableView.cellForRow(at: indexPath)
//use the cell object and do what you want 
}
相关问题