簡體   English   中英

NSRangeException,原因:'試圖將表視圖滾動到越界......'

[英]NSRangeException, reason: 'Attempted to scroll the table view to an out-of-bounds...'

有一個 UITableView,我正在用 ChatMessage 對象填充它,我將它保存在按發送日期分組的字典中,就像這樣var groupedMessages = [Date : [ChatMessage]]()我也將鍵保存在var keys = [Date]()

設置節和出列到行中工作得很好。 下面的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
            ...

        }

就我而言,我忘記添加委托和表視圖的數據源 添加后,我的代碼開始工作。

出現此錯誤是因為您的表格無法找到數據或單元格。

我遇到的問題是我在完成更新之前嘗試滾動。 更正的代碼:

// 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)
        self.MessageList.beginUpdates()
        self.MessageList.insertRows(at: [path], with: .fade)
        self.MessageList.endUpdates()
        self.MessageList.scrollToRow(at: path, at: .bottom, animated: true)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM