繁体   English   中英

无法将新行插入具有动态数量的节和行的UITableView中

[英]Unable to insert new row to UITableView with dynamic number of Sections And Rows

我有一个tableView具有动态的节数,每个节都有动态的行数。

我的数据源数组如下所示

var detailsList = [[Any]]()

但是我确实知道将添加到列表中的类型,并且它们将以特定顺序添加。 让我们考虑这些类型将是A,B,C。

根据来自API的数据可用性,将填充detailsList 因此,数组看起来像这样:

[[A, A, A, A], [B, B, B], [C, C, C]]

在此示例中,tableView具有3个部分,numberOfRows取决于子数组计数。

这是dataSource的样子

    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)

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

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

问题是您应该在“ 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 ,有一种特殊的方法insertSections

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM