swift - NSRangeException,原因 : 'Attempted to scroll the table view to an out-of-bounds...'

标签 swift uitableview nsrangeexception

有一个 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/

相关文章:

ios - AVAssetWriterInput - 黑屏,长达 46 小时

iOS:Tableview 多选 - AccessoryCheckmark 检查可重复使用的单元格

objective-c - appearanceWhenContainedIn 无法按预期使用 UITableView 和 UINavigationController

ios - 在 ViewController 中使用带有外部数据源和 UITableView 的自定义 UITableViewCell

objective-c - NSMutableRLEArray objectAtIndex:effectiveRange::越界

ios - 谷歌分析在 ios 崩溃前的最后一个屏幕

ios - NSRange 在 for 循环中改变自身

ios - 使用 managedObjectContext 属性保存自定义核心数据对象是否正确

swift - 为 swift 包添加 swift 扩展

ios - 如何在原型(prototype)单元格中使用 UIImageView 在 UITableView 中创建视差效果