![](/img/trans.png)
[英]How to pass a value from the TableView controller to a customCell class
[英]how can I reset all switches in tableview from CustomCell
我已經將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)
}
}
我現在需要做的是確保在打開一個開關時,關閉其他行中的所有其他開關。 表格行這樣加載
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
閉包時,閉包的提供者必須根據需要更新其數據模型並重新加載表視圖。
您需要將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()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.