首页 > 解决方案 > 例外:尝试插入第 0 节,但更新后只有 0 节

问题描述

我有一个 UITableView 将聊天消息显示为 ViewCells。

我正在保存聊天消息var groupedMessages = [Date : [ChatMessage]]()

我正在使用groupedMessagesas 表部分的键。

下面是我的 sendChatMessage 函数的代码片段。

else部分工作得很好。但应用程序在if错误部分崩溃attempt to insert section 0 but there are only 0 sections after the update

在 stackoverflow 上发布了几种解决方案,我相信我已经完成了其中提到和引用的所有内容,但无法使其正常工作。谁能看到我的错误在哪里?

非常感谢您的帮助 !!!

...
if (self.groupedMessages.count == 0) {
    let tsp = newMessage.tsp
    let message: [ChatMessage] = [newMessage]
    self.groupedMessages = [tsp! : message]
    self.MessageList.insertSections(IndexSet(integer: 0), with: .none)
    let path = IndexPath(row: 0, section: 0)
    self.MessageList.insertRows(at: [path], with: .fade)
    self.MessageTextField.text = nil
    self.MessageList.scrollToRow(at: path, at: .top, animated: false)
    self.SendMessageButton.loadingIndicator(false)
} else {
    self.groupedMessages[self.keys.last!]?.append(newMessage)
    let path = IndexPath(row: self.groupedMessages[self.keys.last!]!.count-1, section: self.keys.count-1)
    self.MessageList.insertRows(at: [path], with: .fade)
    self.MessageTextField.text = nil
    self.MessageList.scrollToRow(at: path, at: .bottom, animated: true)
    self.SendMessageButton.loadingIndicator(false)
}
...

这是我的实现numberOfSectionsnumberOfRowsInSection

func numberOfSections(in tableView: UITableView) -> Int {
        return self.keys.count
    }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.groupedMessages[keys[section]]!.count
    }

标签: swiftuitableview

解决方案


insertRows插入部分后无需调用。在insertSection表格调用之后numberOfRowsInSection,并且由于您已经更新了模型(groupedMessages),一切都会好起来的。如果您需要随后滚动或做其他事情,您可以将 insertSection 包装在一个performBatchUpdates:completion:调用中。

我也怀疑你的numberOfSections方法是错误的......但这取决于是什么self.keys。什么是 self.keys?您似乎没有在此代码中更新它。


推荐阅读