swift - 例外:尝试插入第 0 节,但更新后只有 0 节
问题描述
我有一个 UITableView 将聊天消息显示为 ViewCells。
我正在保存聊天消息var groupedMessages = [Date : [ChatMessage]]()
。
我正在使用groupedMessages
as 表部分的键。
下面是我的 sendChatMessage 函数的代码片段。
- 该
if
部分处理我开始全新对话的情况。 - 该
else
部分将消息附加在 TableView 的底部。
这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)
}
...
这是我的实现numberOfSections
和numberOfRowsInSection
func numberOfSections(in tableView: UITableView) -> Int {
return self.keys.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.groupedMessages[keys[section]]!.count
}
解决方案
insertRows
插入部分后无需调用。在insertSection
表格调用之后numberOfRowsInSection
,并且由于您已经更新了模型(groupedMessages
),一切都会好起来的。如果您需要随后滚动或做其他事情,您可以将 insertSection 包装在一个performBatchUpdates:completion:
调用中。
我也怀疑你的numberOfSections
方法是错误的......但这取决于是什么self.keys
。什么是 self.keys?您似乎没有在此代码中更新它。
推荐阅读
- python - 沿 3d 线插入点
- mongodb - 如何使用排序规则使用正则表达式过滤带有重音的单词
- node.js - 在服务器上注销时浏览器未清除 cookie,但会清除 localhost 的 cookie
- excel - 如何将参数传递给 Laravel Excel 的导出文件以进行 DB 查询
- c# - 创建多个 PDF 的问题
- c++ - 如何将 cMessage 类型转换为消息定义类型
- html - 如何根据从另一个相同文本区域的删除突出显示只读文本区域?
- python - 无法在基本 conda env 之外启动 jupyter 服务器
- c++ - 通过 Windows 终端访问 C++ ASCII 代码
- javascript - Selenium/BS4 JS 执行引发“消息:TypeError:arguments[0].setAttribute 不是函数”