4

Got a UITableView that I'm populating with ChatMessage objects, that I keep in a Dictionary that is grouped by date sent like so var groupedMessages = [Date : [ChatMessage]]() I'm also keeping keys in var keys = [Date]()

Setting sections and dequeueing into rows works just fine. Also insertRows below works and adds the message as a new UITableViewCell as expected and at the correct position.

However, the App crashed at the scrollToRow call with error 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
            ...

        }
Bernhard Engl
  • 243
  • 1
  • 2
  • 12

2 Answers2

1

In my case, I forget to add delegate, and datasource of table view. After adding this, my code started working.

This error occurs because your table is not able to find the data or cell.

-2

The problem I had was that I tried to scroll before finishing the update. Corrected code:

// 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)
Bernhard Engl
  • 243
  • 1
  • 2
  • 12
  • 2
    Delete both lines `beginUpdates` and `endUpdates` anyway. They have no effect around a single `insert` operation. And please conform to the naming convention and name variables and functions with starting lowercase letter. – vadian Jan 20 '20 at 16:22
  • @vadian: thanks for your input. Got another question around that code section here https://stackoverflow.com/questions/59865792/problem-with-row-insertion-in-a-uitableview Would really appreciate your help there as I'm stuck and can't seem to get out – Bernhard Engl Jan 23 '20 at 07:19