ios - 如何从 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
解决方案
这将是设置switchAction
每个单元格的控制器的责任。
当switchAction
调用闭包时,闭包的提供者必须根据需要更新其数据模型并重新加载表视图。
您需要将您的switchAction
in更新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()
}
}
推荐阅读
- r - 仅将任意图像添加到传单地图
- python - to_date() 的 cx_Oracle 字符串表示会引发错误
- angular - 如何使用 Angular CurrencyPipe 显示便士(个)位置?
- haskell - Haskell 中的并行“任何”或“全部”
- python - 在 Python 递归函数中确定偶数/奇数迭代
- r - 提取最短匹配字符串正则表达式
- python - 如何在python中比较字符串时间
- node.js - 如何在代码中使用公钥功能实现 openssl smime 加密
- node.js - Google Analytics Reporting v4 中的过滤器问题
- ansible - 在 Ansible 库存组中使用通配符无法按预期工作