首页 > 解决方案 > 删除行时 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)


    }
 }

标签: iosswiftuitableviewrownsuserdefaults

解决方案


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
        }

更改复选框单击


推荐阅读