【问题标题】:Animating inserting a new row into a new section in a UITableView动画将新行插入 UITableView 的新部分
【发布时间】:2018-06-21 16:26:33
【问题描述】:

问题很简单。

我正在尝试将新行添加到新部分中。

更新代码:

func updateTableView(sessions: [Sessions]) {
   self.foundSessions = sessions
    if self.numberOfSections(in: self.tableView) == 0 {
        self.tableView.beginUpdates()
        self.tableView.insertSections([0], with: .automatic)
        self.tableView.endUpdates()
    }
    for i in 0..<self.foundSessions.count {
       self.tableView.beginUpdates()
       self.tableView.insertRows(at: [IndexPath(row: i, section: 0)], with: .automatic             
       self.tableView.endUpdates()
    }
}

UITableViewDataSource代码:

override func numberOfSections(in tableView: UITableView) -> Int {
     if foundSessions.isEmpty { return 0 }
     return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return foundSessions.count
}

还有错误:

由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“尝试插入第 0 节,但更新后只有 0 节

显然,该部分似乎没有被插入。如果我取出insertRows,最终会出现空白部分,如顶部的tableFooterView 所示。我已经听从了herehereherehere这些帖子的建议,并阅读了相应的Apple Documentation,显然无济于事。

那里有任何 iOS 专家能够以我的方式向我展示错误吗?

编辑:更多调试信息 - updateTableView 在异步函数的回调中被调用。我将所有这些代码封装在一个 DispatchQueue.main.async 块中,试图纠正这种情况,但是没有成功。

【问题讨论】:

    标签: ios swift uitableview uikit


    【解决方案1】:

    尝试将所有更新放到部分中,并将其放在一个块中,开始...结束,如下所示

    self.tableView.beginUpdates()
    self.tableView.insertSections([0], with: .automatic)
    for i in 0..<self.foundSessions.count {
        self.tableView.insertRows(at: [IndexPath(row: i, section: 0)], with: .automatic
    }
    self.tableView.endUpdates()
    

    【讨论】:

    • 那是我的第一次尝试:/ 应该这样写。谢谢你的回答!
    • 我不太确定为什么会这样,但很快就会给出真正的原因。
    猜你喜欢
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    相关资源
    最近更新 更多