【问题标题】:App crashes when I want to use tableview.deleteRows(at: , with: )当我想使用 tableview.deleteRows(at: , with: ) 时应用程序崩溃
【发布时间】:2016-11-11 19:53:35
【问题描述】:

我已经看到了很多关于这个主题的主题,但我仍然有错误......

这是我在 tableview 委托方法中的代码(当用户滑动并单击单元格上的删除按钮时调用):

self.tableView.beginUpdates()

if self.data[sectionType]!.isEmpty {
    self.data.removeValue(forKey: sectionType)
}

self.tableView.deleteRows(at: [indexPath], with: .fade)
self.tableView.endUpdates()

我已经实现了这样的 numberOfSections 委托方法:

func numberOfSections(in tableView: UITableView) -> Int {
    return data.count
}

这是我得到的错误:

*** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“UITableView 内部错误:无法生成具有旧节数:1 和新节数:0 的新节图”

如果我将 deleteRows(in tableView) 方法替换为 reloadData()...

我检查了断点,当错误发生时我输入了 if 条件。所以数据被更新了(removeValue() 调用后的 0 元素),我调用了 deleteRows 方法。

感谢您的帮助。

【问题讨论】:

  • 你使用 numberOfRowsInSection 方法了吗?

标签: ios swift uitableview


【解决方案1】:

您是要删除行还是部分?

if self.data[sectionType]!.isEmpty {
    self.data.removeValue(forKey: sectionType)
}

建议您尝试删除一个部分。如果您是,则应在其后加上此类内容:

let indexSet = NSMutableIndexSet()
indexSet.addIndex(section)
self.tableView.deleteSections(indexSet, withRowAnimation: .fade)

如果您尝试删除一行,请将顶部更改为如下内容:

if self.data[sectionType]!.isEmpty {
    self.data[sectionType].remove(at: rowToRemove)
}

【讨论】:

  • 你完全正确!我想删除一个部分。我没有使用正确的 UITableView 方法。 deleteSections() 方法解决了我的问题 :) 谢谢!!
【解决方案2】:

看起来您可能要删除该部分中的所有行,而不是一个单元格。

我假设self.data 是一个字典,其中键是节,值是包含单元格信息的数组。 而不是删除字典的键。就像你在这里一样......

self.data.removeValue(forKey: sectionType)

您可能希望访问该部分并仅删除该行。像这样的...

data[sectionType]?.remove(at: indexPath.row)

我假设您对方法 numberOfRowsInSection: 的返回值类似于...

return data[sectionType]?.count

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-03
    • 2022-07-31
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 2019-10-12
    • 2016-06-20
    • 2018-04-27
    相关资源
    最近更新 更多