ios - 删除行时 UITableView 中的复选框不起作用
问题描述
我已经在 UITableView 控制器中实现了一个复选框,它工作得很好,但是当复选框被选中并且 tableview 中的行被删除并且当我向 tableview 添加新行时它被选中。这是我的项目的链接:https ://files.fm/f/tepkz2du 我认为这与删除一行有关,索引路径搞砸了。
更新代码:
cellForRowAt:
if let btnChk3 = cell?.contentView.viewWithTag(100) as? UIButton {
btnChk3.addTarget(self, action: #selector(checkboxClicked(_ :)), for: .touchUpInside)
}
if let btnChk2 = cell.contentView.viewWithTag(22) as? UIButton {
btnChk2.isSelected = UserDefaults.standard.integer(forKey: myarray[indexPath.row]) == (indexPath.row + index) ? true : false
}
复选框单击
let defaults = UserDefaults.standard
let myarray = defaults.stringArray(forKey: "ScheduleArray") ?? [String]()
if sender.tag == 100 {
if let btnChk2 = cell.contentView.viewWithTag(22) as? UIButton {
if btnChk2.isSelected == true {
btnChk2.isSelected = false
UserDefaults.standard.set(-1, forKey: myarray[(indexPath?.row)!] )
UserDefaults.standard.synchronize()
}else{
btnChk2.isSelected = true
UserDefaults.standard.set((indexPath?.row)! + index, forKey: myarray[(indexPath?.row)!])
UserDefaults.standard.synchronize()
}
}
sender.isSelected = false
}
编辑风格 == .delete:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if tableView == ScheduleTableView{
let defaults = UserDefaults.standard
var myarray = defaults.stringArray(forKey: "ScheduleArray") ?? [String]()
print(myarray)
myarray.remove(at: indexPath.row)
defaults.set(myarray, forKey: "ScheduleArray")
ScheduleTableView.deleteRows(at: [indexPath], with: .fade)
}
}
解决方案
if let btnChk2 = cell.contentView.viewWithTag(22) as? UIButton {
btnChk2.isSelected = UserDefaults.standard.integer(forKey: myarray[indexPath.row]) == (indexPath.row + index) ? true : false
}
在某一方面的变化cellForRowAt
let defaults = UserDefaults.standard
let myarray = defaults.stringArray(forKey: "ScheduleArray") ?? [String]()
if sender.tag == 100 {
if let btnChk2 = cell.contentView.viewWithTag(22) as? UIButton {
if btnChk2.isSelected == true {
btnChk2.isSelected = false
UserDefaults.standard.set(-1, forKey: myarray[(indexPath?.row)!] )
UserDefaults.standard.synchronize()
}else{
btnChk2.isSelected = true
UserDefaults.standard.set((indexPath?.row)! + index, forKey: myarray[(indexPath?.row)!])
UserDefaults.standard.synchronize()
}
}
sender.isSelected = false
}
更改复选框单击
推荐阅读
- spring - 从 yml 文件中读取数据的服务类
- python - 动态添加属性会创建不需要的别名
- java - 为什么 Flux.zip 接受预定义函数而不接受匿名函数?
- docker - 无法在 docker 容器中运行 jupyterhub
- python - 在 Pandas 中将字符串转换为时间
- python - 建议的最大任务大小为 100 KB 如何使用 python spark 解决此问题 如何在 python pyspark 中解决此问题
- qt - 如何读取 main.qml 中的 listmodel 角色属性?
- excel - 如何从 MSHTML.IHTMLElementCollection 中选择特定表
- excel - Excel Pivottable 刷新(2010 与 2016) - 为什么在 2016 年不工作,但在 2010 年工作?
- sql - Postgresql 约束在时间戳之间没有重叠