有一个 UITableView,我用 ChatMessage 对象填充,我保存在一个字典中,该字典按发送日期分组,如下所示 var groupedMessages = [Date : [ChatMessage]]()
我还在 var keys = [Date]()
中保留 key
设置部分和出列成行工作得很好。
还有insertRows
下面的作品并按预期将消息添加为新的 UITableViewCell 并在正确的位置。
但是,该应用程序在 scrollToRow
处崩溃。调用错误 NSRangeException, reason: 'Attempted to scroll the table view to an out-of-bounds row (2) when there are only 2 rows in section 1.
@IBAction func sendMessage(_ sender: Any) {
// create new ChatMessage object
var newMessage = ChatMessage()
let now = Date()
newMessage.tsp = now
newMessage.message = self.MessageTextField.text
newMessage.sender = Globals.shared.user
// append to grouped messages
self.groupedMessages[self.keys.last!]?.append(newMessage)
var path = IndexPath(row: self.groupedMessages[self.keys.last!]!.count-1, section: self.keys.count-1)
print("PATH: ", path)
self.MessageList.beginUpdates()
self.MessageList.insertRows(at: [path], with: .fade)
print("PATH 2: ", path)
self.MessageList.scrollToRow(at: path, at: .bottom, animated: true)
self.MessageList.endUpdates()
// call api to store sent message
...
}
最佳答案
就我而言,我忘记了 添加委托(delegate)和数据源的 TableView 。添加后,我的代码开始工作。
发生此错误是因为您的表格无法找到数据或单元格。
关于swift - NSRangeException,原因 : 'Attempted to scroll the table view to an out-of-bounds...' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59826208/