swift - Swift tableview 单元格不使用不同的标识符保存状态
问题描述
我对细胞的重复使用感到非常困惑。
我有一张桌子,每个单元格都是一个带有开关的单元格。如果我切换开关,我将该单元格的背景颜色设置为不同的颜色。但是,每次我滚动这些更改都不会持续存在。
我正在继承 UITalbeViewCell 来创建我自己的自定义单元格。每个单元格都有不同的标识符。但是,当我滚动表格时,我对单元格所做的任何更改仍然无法保存。我读过类似的问题,但没有一个有效。一些我建议的子类,一些建议使用不同的标识符,我也这样做了......
这是我的表格视图的代码。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let key = Array(dataSource[indexPath.section].keys)[indexPath.row]
let cell = CellWithSwitch.init(style: .subtitle, reuseIdentifier: key)
cell.awakeFromNib()
let val = Array(dataSource[indexPath.section].values)[indexPath.row]
cell.switchView?.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
if let index = key.firstIndex(of: "."){
cell.textLabel?.text = String(key.suffix(from: key.index(index, offsetBy: 1)))
}else{
cell.textLabel?.text = key;
}
cell.switchView?.setOn(val, animated: true)
return cell
}
解决方案
您可以更改数组switchChange
值
让我将数组用于切换,如下所示:
var arrSwitch = [false,false,false,false,false,false,false,false,false,false]
下面是我的cellForRowAt
方法
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! customCell
cell. switchView.setOn(self.arrSwitch[indexPath.row], animated: false)
cell. switchView.tag = indexPath.row
cell. switchView.addTarget(self, action: #selector(self.onSwitchTap(_:)), for: .valueChanged)
return cell
}
这是我的onSwitchTap
行动
@IBAction func onSwitchTap(_ sender: UISwitch) {
self.arrSwitch[sender.tag] = !self.arrSwitch[sender.tag]
}
现在在滚动时,它将保留您所做的最后更改。
推荐阅读
- windows - 64 位 Ntdll 有 x86 指令集吗?
- r - 无法从脚本导出环境变量
- mongodb - 使用 Tailable ReactiveMongo 扩展 Spring WebFlux
- ios - XCode 11.4 - 在 UITest 中重新安装应用程序失败:“找不到已安装的应用程序”
- java - 如何在从 xml 文件加载配置时给出 jooq 生成器自定义策略的地址?
- c# - RestSharp 错误:从 result.Data 中给出 null
- php - 显示带有翻译的产品表中的所有数据,但如果产品没有翻译,则使用默认语言显示
- react-native - Razorpay sucessCallBack() 后 React Native 应用程序关闭
- php - 如何在 php 中使用 get 方法发送数据
- javascript - 调用一个动作来更新本地存储(无需 API 调用)——redux 持久化,反应原生