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

时间:2018-01-15 14:47:50

标签: swift xcode

我正在进行黑暗模式切换,当我打开它时,我只缺少单元格将其颜色更改为黑色,这怎么办?感谢。

2 个答案:

答案 0 :(得分:0)

你可以像下面这样做。

tableView.cellForRow(at: indexPath)?.backgroundColor = UIColor.red

答案 1 :(得分:0)

只需将此方法添加到您的类中,并将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
}