ios - 如何知道 UITableView 何时完成 reloadData?

标签 ios swift uitableview reloaddata

我的实时应用程序因以下问题而崩溃。我进行了大量搜索,现在我明白我必须确保在调用 scrollToRow 之前重新加载该表。我见过很多解决方法,但我不确定哪一个会真正起作用。我试过在主线程上调用 scrollToRow 或在延迟后调用,但这并没有解决我的问题。我已经加载了更多(分页)实现,如果我在延迟后使用 fix 调用 scrollToRow 会搞砸。

我们如何解决这个问题?如何确定表已完成重新加载?

这个解决方案看起来不错,但对我不起作用。 https://stackoverflow.com/a/18812830/11957965

由于崩溃只发生在实时应用程序上,我无法在开发测试期间重现它,所以我想确保我有一个有效的修复。

崩溃

[UITableView _contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:usingPresentationValues:]: section (0) beyond bounds (0).

代码

if result!.data!.items!.count > 0 {
    self.msgTable.reloadData()

    let lastIndexPath = IndexPath(row: 0, section: 0)
    self.msgTable.scrollToRow(at: lastIndexPath, at: UITableView.ScrollPosition.top, animated: false)
}

performBatchUpdates 解决方案

// This one crashes
if #available(iOS 11.0, *) {
    self.mesgTable.performBatchUpdates({
        let index = IndexPath(row: 0, section: 0)
        self.mesgTable.insertRows(at: [index], with: .none)
    }, completion: { (success) in
        if self.currentPage == 1 && self.dataSource.count > 0 {
            let lastIndexPath = IndexPath(row: 0, section: 0)
            self.mesgTable.scrollToRow(at: lastIndexPath, at: UITableView.ScrollPosition.top, animated: false)
        }
    })
} else {
    if self.currentPage == 1 && self.dataSource.count > 0 {
        let lastIndexPath = IndexPath(row: 0, section: 0)
        self.mesgTable.scrollToRow(at: lastIndexPath, at: UITableView.ScrollPosition.top, animated: false)
    }
}

崩溃

** 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 (1) 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 (0 inserted, 0 deleted).'

最佳答案

您可以将 performBatchUpdates 与完成处理程序一起使用,而不是 reloadData。使用此方法,您可以手动插入项目并控制 IndexPaths。这样你就可以插入动画并滚动完成动画。 查看此文档以供引用:

https://developer.apple.com/documentation/uikit/uitableview/2887515-performbatchupdates?language=objc

关于ios - 如何知道 UITableView 何时完成 reloadData?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57594982/

相关文章:

ios - Swift 只允许选择一个单元格

ios - 重命名uitableview部分的标题

ios - 如何制作 float View ?

ios - 将 swift 连接到 FirebaseDatabase

ios - 运行时遇到错误(域 = LaunchServicesError,代码 = 0)

ios - UIPageViewController Swift 中的当前页面索引

ios - 如何计算不同方向的 iOS 11 尺寸?

ios - 在 TextKit 中嵌入 youtube 视频

ios - 在 iOS 中解码 unicode 字符串

ios - ionic : Dropdown bug inside iframe ios