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
...
}