如何在单击关闭按钮时从数组中删除数据

How to remove data from array on click of close button

我有一个数组,我需要在单击 "close" 时添加和删除单元格数据,它是 header 部分

中的 UIButton

我正在循环数组并获取行,对于部分我使用了静态数据并在 indexPaths 中追加,然后在

之后
tblSideNav.deleteRows(at: indexPaths, with: .fade) 

如上行开始执行应用程序崩溃

 var menusArray = [sideNavStruct(isOpend: true, menuImg: "user", menuTitle: "Profile", subMenu: ["My Profile", "Distributor Profile"]), sideNavStruct(isOpend: true, menuImg: "user", menuTitle: "Reports", subMenu: ["Stock Report", "NFR Report", "RTD”])]

    @objc func handleOpenCloseCell() {
    let section = 0
    var indexPaths = [IndexPath]()
    for row in menusArray[section].subMenu.indices {
        let indexPath = IndexPath(row: row, section: section)
        indexPaths.append(indexPath)
    }
    print(indexPaths.count)
    print(menusArray[section].subMenu[0])
    menusArray[section].subMenu[0].removeAll()
    tblSideNav.deleteRows(at: indexPaths, with: .fade)
}

我的应用程序在 tblSideNav.deleteRows(at: indexPaths, with: .fade) 崩溃:

Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (7) must be equal to the number of rows contained in that section before the update (2), plus or minus the number of rows inserted or deleted from that section (0 inserted, 2 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).

我找不到问题

首先,您调用的 deleteRows 没有必需的 beginUpdates 和 endUpdates。

tableView.beginUpdates()
tableView.deleteRows(at: indexPaths, with: .fade)
tableView.endUpdates()

如果您的委托函数在更新后未返回正确的行数,也会发生同样的错误。

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return rowCount
}

我认为更好的做法是 change/empty 存储行的变量 information/data 并简单地调用 reloadData()。