首页 > 解决方案 > 如何从 CustomCell 重置 tableview 中的所有开关

问题描述

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

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 都关闭。表格行是这样加载的

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 有两种类型,saveData 方法如下所示

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

更改 Switch 时表格不会更新,但由于该类一次只处理一个行操作,我不确定如何从自定义 Switch 类更新 TableView

标签: iosswiftuitableviewuiswitchcustom-cell

解决方案


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

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

您需要将您的switchActionin更新cellForRowAt为以下内容:

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()
    }
}

推荐阅读