ios - 无法将新行插入具有动态部分和行数的 UITableView
问题描述
我有一个带有动态节数的 tableView,每个节都有动态的行数。
我的数据源数组看起来像这样
var detailsList = [[Any]]()
但是,我确实知道将添加到列表中的类型,并且它们将按特定顺序添加。让我们考虑这些类型是 A、B、C。
根据来自 API 的数据的可用性,detailsList
将被填充。因此数组看起来像这样:
[[A, A, A, A], [B, B, B], [C, C, C]]
在此示例中,tableView 有 3 个部分,numberOfRows 取决于子数组计数。
这是数据源的样子
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return detailsList.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return detailsList[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let _ = detailsList[indexPath.section] as? [A] {
return cellA
} else if let _ = detailsList[indexPath.section] as? [B] {
return cellB
} else if let _ = detailsList[indexPath.section] as? [C] {
return cellC
} else if let _ = detailsList[indexPath.section] as? [D] {
return cellD
}
}
我面临的问题是当我想插入一个部分时。
让我们在添加数组之前说 DataSource 看起来像这样
detailsList = [[A, A, A, A], [B, B, B], [C, C, C]]
添加新部分后,数据源看起来像这样
detailsList = [[A, A, A, A], [B, B, B], [C, C, C], [D, D, D, D]]
我不能说
tableView.insertRows(at: [indexPath], with: .none)
应用程序崩溃并出现以下异常
由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无效更新:无效的节数。更新后表视图中包含的节数(4)必须等于更新前表视图中包含的节数(3),加上或减去插入或删除的节数(0插入,0已删除)。
但如果我说
tableView.reloadData()
它按预期工作。
还有另一种插入新部分的方法吗?
解决方案
您正在添加一个部分,因此您需要使用
let indexSet = IndexSet( integer:4)
tableView.insertSections( indexSet, with:.fade)
推荐阅读
- c++ - 如何纠正这个程序?
- web-scraping - 使用 ImportHTML 和 Google 表格进行网络抓取
- javascript - 如何在 Vis.js / D3.js 中以圆形模式排列节点
- angular - 模块“AppModule”导入的意外指令“MatAutoCompleteTrigger”。请添加@NgModule 注释
- python - 在运行的 bash 脚本中重定向 pip 安装消息
- python - 在 Keras 中检查模型输入以获取验证数据时出错
- javascript - 合并(更新)数组中的相同对象
- java - Jersey MultiPartRequest 接收 null
- html - 垂直对齐不适用于纯文本?
- php - OpenLDAP PHP 添加生日属性