【问题标题】:UITableView multiple insertSections to same indexUITableView多个insertSections到同一个索引
【发布时间】:2016-02-15 07:36:08
【问题描述】:

我有一个要在 UITableView 中显示的数据集。我想作为第 0 部分插入的所有新数据集。通常,我会得到很多集,然后我想一次将它们推送到顶部。这看起来像

tableView.beginUpdates()
repeat {
  data.append(dataProvider.nextDataSet())
  tableView.insertSections(NSIndexSet(index:0), withRowAnimation: .Automatic)
} while dataProvider.hasMoreData
tableView.endUpdates()

虽然我的 data 数组与我想要的完全一样,但我的应用程序崩溃时会说:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (5) must be equal to the number of sections contained in the table view before the update (0), plus or minus the number of sections inserted or deleted (2 inserted, 0 deleted).'

我制作了a little sample project on GitHub,通过这样做来重现这个问题

numSections += 1
tableView.insertSections(NSIndexSet(index:0), withRowAnimation: .Automatic)

五次 (link) 其中 numSections 是节数,每个节的行数始终为 3。它再次说我只插入了 2 个部分,而实际上我确实插入了 5 个。

我在这里误解了什么?为什么 tableView 认为我只给了它 2 个新部分?当然,如果我只给它2个部分,它认为我只给它1个。:-I

【问题讨论】:

    标签: ios swift uitableview sections


    【解决方案1】:

    就显示数据的顺序而言,您插入的部分索引无关紧要,这由您的数据数组控制。您应该在不同的索引处插入这些部分,因此请使用 numSections 变量来控制它。

    我希望如果您将开始和结束更新移动到循环中,它也会起作用。问题是您不知道表格视图在内部是如何工作的,据我所知,您看到的问题没有记录在案,但是在与您的基础数据不匹配的索引处插入部分是不合逻辑的。

    【讨论】:

      【解决方案2】:

      insertSections 将在endUpdates() 的末尾实际执行。所以在实际场景中,没有插入这些部分,您指定的是增加了部分。

      这会奏效。如果您知道要插入的节数,则使用此方法

          tableView.beginUpdates()
          numSections += 5
          tableView.insertSections(NSIndexSet(indexesInRange: NSMakeRange(0, 5)), withRowAnimation: .Automatic)
          tableView.endUpdates()
      

      以上代码为github代码。它可以根据您的实际代码进行更改。不要循环或多次调用insertSections()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-22
        • 2021-10-30
        • 2017-10-22
        • 1970-01-01
        • 2017-11-25
        • 1970-01-01
        相关资源
        最近更新 更多