【问题标题】:Unable to add a row to a section in UITableView无法向 UITableView 中的部分添加行
【发布时间】:2017-01-25 03:36:59
【问题描述】:

我的自定义单元格中有一个收藏按钮。在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 _endCellAnimationsWithContext:] 中的断言失败,/BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3600.6.21/UITableView.m:1594

由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'无效更新:第1节中的行数无效。更新后(2)表视图中包含的节数必须等于节数包含在更新前的表视图中 (1),加上或减去插入或删除的节数(0 插入,0 删除)。'

【问题讨论】:

  • 请出示您的numberOfRowsInSection代码;它没有准确反映更新的行数
  • 已编辑,我还在else子句中放了一条print语句,显示收藏部分的行数成功增加到1
  • 您正在将新行添加到名为 favorites 的数组中,但 numberOfRowsInSection 正在返回名为 favoriteFoods 的数组的计数
  • 这是favorites.append 的错字,应该是favoriteFoods.append
  • 对不起,这是从旧代码中提取的错字。我的工作代码有favorites 两个

标签: swift uitableview insert swift3 row


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您正在将新行添加到名为 favorites 的数组中,但 numberOfRowsInSection 正在返回名为 favoriteFoods 的数组的计数

    【讨论】:

    • 抱歉,这是从旧代码中提取的拼写错误。我的工作代码都有favorites
    • 尝试将favorites.append(allFood[(indexPath?.row)!])移到beginUpdates之后
    猜你喜欢
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多