I have implemented a checkbox in UITableView controller, it works perfectly but when the checkbox are selected and the rows in the tableview are deleted and the when I add a new row to the tableview it gets selected.
Here is a link to my project: https://files.fm/f/tepkz2du
I think it has something to do with when a row is delete, the index path is messed up.
UPDATED CODE:
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
}
checkboxClicked
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
}
editingStyle == .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)
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…