如何从 CustomCell 重置 tableview 中的所有开关

how can I reset all switches in tableview from CustomCell

我已经将 Switch 设置为 tableView 单元格的一部分,并设置了 CustomCell class 来处理操作,class 看起来像这样

class SwitchTableViewCell: UITableViewCell {
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var `switch`: UISwitch!

    var switchAction: ((Bool) -> Void)?

    @IBAction func switchSwitched(_ sender: UISwitch) {
        switchAction?(sender.isOn)
    }
}

我现在要做的是保证当一个Switch打开时,其他行的所有Switch都关闭。 table 行是这样加载的

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let thisRow = rowData[indexPath.row]

    switch thisRow.type {
    case .text:
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "textfieldCell", for: indexPath) as? MovingTextFieldTableViewCell else {
            Logger.shared.log(.app, .error, "Could not load TextFieldTableViewCell")
            fatalError()
        }
        cell.textField.textFieldText = thisRow.data as? String
        cell.textField.labelText = thisRow.title
        cell.dataChanged = { text in
            thisRow.saveData(text)
        }
        cell.errorLabel.text = nil
        return cell
    case .switch:
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "switchCell", for: indexPath) as? SwitchTableViewCell else {
            Logger.shared.log(.app, .error, "Could not load SwitchTableViewCell")
            fatalError()
        }
        cell.label.text = thisRow.title
        cell.switch.isOn = thisRow.data as? Bool ?? false
        cell.switchAction = { isOn in
            thisRow.saveData(isOn)
        }
        return cell
    }
}

每行中的 thisRow 有两种类型 (Text/Switch),saveData 方法如下所示

func saveData(_ data: Any?) {
    self.data = data
}

table 在 Switch 更改时不会更新,但由于 class 一次只处理一行操作,我不确定如何从自定义 Switch 更新 TableView class

这将是设置每个单元格 switchAction 的控制器的责任。

调用 switchAction 闭包时,闭包的提供者必须根据需要更新其数据模型并重新加载 table 视图。

您需要将 cellForRowAt 中的 switchAction 更新为如下内容:

cell.switchAction = { isOn in
    thisRow.saveData(isOn)

    // This switch is on, reset all of the other row data
    if isOn {
        for (index, row) in rowData.enumerated() {
            if index != indexPath.row && row.type == .switch {
                row.saveData(false)
            }
        }

        tableView.reloadData()
    }
}