我正在使用一个UITableView,它有一个带UISwitch的单元。我有四个TableViewCell,每个都来自同一个原型cell。但是,当我切换开关时,TableViewCellForItemAt:
部分中的变量的唯一方式是当我拉动TableView使其离开屏幕,然后重新加载可重用单元格。切换开关时如何使这些变量刷新?
这是我的代码:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "onOffCell", for: indexPath) as! SettingsCellTableViewCell
if indexPath.section == 0 {
cell.textLabel?.text = OLLItems![indexPath.row]._text
if indexPath.row == 0 {
GlobalData.AllGlobalData.OLLImageState = cell.state //GlobalData.AllGlobalData.OLLImageState is an struct in another file
print("OLLImageState \(GlobalData.AllGlobalData.OLLImageState)")
}
if indexPath.row == 1 {
GlobalData.AllGlobalData.OLLAlgState = cell.state
print("OLLAlgState \(GlobalData.AllGlobalData.OLLAlgState)")
}
}
if indexPath.section == 1 {
cell.textLabel?.text = PLLItems![indexPath.row]._text
if indexPath.row == 0 {
GlobalData.AllGlobalData.PLLImageState = cell.state
print("PLLImageState \(GlobalData.AllGlobalData.PLLImageState)")
}
if indexPath.row == 1 {
GlobalData.AllGlobalData.PLLAlgState = cell.state
print("PLLAlgState \(GlobalData.AllGlobalData.PLLAlgState)")
}
}
return cell
}
最佳答案
试着这样做
下面的代码在我的回购协议中可以正常工作,但我对它做了一些修改,以证明您的方案是正确的
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "switchCell", for: indexPath) as! SwitchContainingTableViewCell
cell.mySwitch.addTarget(self, action: #selector(switchChanged(_:)), for: .valueChanged)
return cell
}
func switchChanged(_ mySwitch: UISwitch) {
guard let cell = mySwitch.superview?.superview as? SwitchContainingTableViewCell else {
return // or fatalError() or whatever
}
self.value = mySwitch.isOn //define var value in your controller or do it locally
let indexPath = itemTable.indexPath(for: cell)
if indexPath.section == 0 {
if indexPath.row == 0 {
GlobalData.AllGlobalData.OLLImageState = self.value
}
}
}
我添加了一个
switch
的目标,在这个目标中,我得到了开关的更改状态。使用cellForItemAt:
可以在state = mySwitch.isOn
中执行相同的操作希望这有帮助!
关于ios - CellForItemAt:索引路径未更新变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55857285/