首页 > 解决方案 > 无法将新行插入具有动态部分和行数的 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()它按预期工作。

还有另一种插入新部分的方法吗?

标签: iosswiftuitableview

解决方案


您正在添加一个部分,因此您需要使用

let indexSet = IndexSet( integer:4)
tableView.insertSections( indexSet, with:.fade)

推荐阅读