【问题标题】:Unable to insert new row to UITableView with dynamic number of Sections And Rows无法将新行插入具有动态部分和行数的 UITableView
【发布时间】:2018-09-04 14:38:07
【问题描述】:

我有一个带有动态节数的 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() 它按预期工作。

还有其他插入新部分的方法吗?

【问题讨论】:

  • 调用 insertRows 时的 indexPath 是什么?

标签: ios swift uitableview


【解决方案1】:

正如错误消息告诉您的那样,您正在尝试插入更多行,但您的数组告诉您的是您需要更多节。为此,您应该使用:

tableView.insertSections(sections: IndexSet, with: UITableViewRowAnimation)

【讨论】:

    【解决方案2】:

    你正在添加一个部分,所以你需要使用

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

    【讨论】:

      【解决方案3】:

      问题是您应该像这样在“beginUpdates”和“endUpdates”方法调用中调用insertRows 方法:

      //update the array first
      detailsList = [[A, A, A, A], [B, B, B], [C, C, C], [D, D, D, D]]
      
      //call insert method inside begin and end updates
      tableView.beginUpdates()
      tableView.insertRows(at: [indexPath], with: .none)
      tableView.endUpdates()
      

      UPD:有一个特殊的方法insertSections添加一个节而不是一行。

      【讨论】:

      • 这不是真的,如果你只做一个添加/删除操作,你不必调用 beginUpdates 和 endUpdates。如果您正在执行多个操作,则必须调用它们,因此它们是批量执行的。
      猜你喜欢
      • 1970-01-01
      • 2017-04-09
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多