我的自定义单元格中有一个“收藏夹”按钮。在tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)中,每当单击“收藏夹”按钮时,我都会设置一个侦听器。现在,我有两个部分。第0节是所有食物,第1节是收藏夹。当我到达endUpdates()时,应用程序将崩溃,并出现NSInternalInconsistencyException异常。tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)函数从不在addFavorites内调用。favoriteFoods已初始化,我从未在代码中的任何其他地方调用过beginUpdatesendUpdates

func addFavorites(sender: UIButton) {
        let touchPoint = sender.convert(CGPoint(x: 0, y: 0), to: companyTableView)
        let indexPath = companyTableView.indexPathForRow(at: touchPoint)

        favorites.append(allFood[(indexPath?.row)!])

        tableView.beginUpdates()
        tableView.insertRows(at: [IndexPath(row: favoriteFoods.count - 1, section: 1)], with: .automatic)
        tableView.endUpdates()
    }

func tableView(_ tableView: UITableView, numberOfRowsInSection
        section: Int) -> Int {
        if (section == 0) {
            return allFood.count
        } else {
            return favorites.count
        }
    }

断言失败-[UITableView\u endCellAnimationsWithContext:],/BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit\u Sim/UIKit-3600.6.21/UITableView.m:1594
由于未捕获异常“NSInternalInconsistencyException”而终止应用程序,原因:“无效更新:第1节中的行数无效。更新后表视图中包含的节数(2)必须等于更新前表视图中包含的节数(1),加上或减去插入或删除的节数(0插入,0删除)。'

最佳答案

我需要在开始和结束更新之间添加companyTableView.insertSections([1], with: .automatic),因为没有预先存在的部分。

09-25 22:27
查看更多