Swift 如何使用开关更改UITableViewCell背景色?

Swift 如何使用开关更改UITableViewCell背景色?,swift,xcode,Swift,Xcode,我正在做一个暗模式开关,当我打开它的时候,我只错过了把它们的颜色变成黑色的细胞,这怎么能做到呢?谢谢。你可以像下面这样做 tableView.cellForRowat:indexPath?.backgroundColor=UIColor.red只需将此方法添加到类中,并将UISwitch值更改附加到此操作: @IBAction func changeColorAction(_ sender: UISwitch) { let visibleCells: [UITableViewCell]

我正在做一个暗模式开关,当我打开它的时候,我只错过了把它们的颜色变成黑色的细胞,这怎么能做到呢?谢谢。

你可以像下面这样做


tableView.cellForRowat:indexPath?.backgroundColor=UIColor.red

只需将此方法添加到类中,并将UISwitch值更改附加到此操作:

@IBAction func changeColorAction(_ sender: UISwitch) {

    let visibleCells: [UITableViewCell] = tableView.visibleCells

    for cell in visibleCells {
        if sender.isOn {
            cell.contentView.backgroundColor = UIColor.darkGray
        }else {
            cell.contentView.backgroundColor = UIColor.white
        }
    }
}
然后,在tableView委托方法中实现这一点:

internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath)

    if switch.isOn {
        cell.contentView.backgroundColor = UIColor.darkGray
    }else {
        cell.contentView.backgroundColor = UIColor.white
    }

    return cell
}

到目前为止,您尝试了什么?我们需要看到更多的代码,但您可能只需要通过调用reloadData来重新加载表中的数据。尽管如此,这些都不起作用,如果你愿意,我可以发送我的代码。