I am trying to create a comments / messages tableView
using Swift and would like for the UITableViewController
to show the last tableViewCell
when the user clicks that "comment room"
I am pulling data from a remote source, (Firebase in this case) to populate each of the tableViewCells
. Once I pull all the data, I configure each cell with the appropriate information. This is done without any error whatsoever.
However, by default, the tableview
shows the cell at the top
I've tried using these to make the tableView
show the last cell but it still performs a visible "scrolling" effect which I would like to remove. For example, take the iMessage app, Instagram's or Snapchat's direct messaging feature. Upon clicking a "chat or comment room", the resulting table (or collectionview
) immediately displays the last cell without visibly scrolling to it
Here is what I tried:
var chatRoomMessages: [FIRDataSnapshot] = []
override func viewDidLoad() {
super.viewDidLoad()
fetchChatRoomCommentsFromServer(chatRoomId: self.chatRoomId) { (snap) in
self.chatRoomMessages.append(snap)
self.tableView.reloadData()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
moveToLastComment()
}
func fetchChatRoomCommentsFromServer(chatRoomId: String, callback: @escaping (FIRDataSnapshot) -> ()) {
DataService.dataService.CHAT_ROOM_REF.child(chatRoomId).child("messages").observe(.childAdded, with: { (snapshot) in
DataService.dataService.MESSAGES_REF.child(snapshot.key).observe(.value, with: { (snap) in
callback(snap)
})
})
}
func moveToLastComment() {
if self.tableView.contentSize.height > self.tableView.frame.height {
// First figure out how many sections there are
let lastSectionIndex = self.tableView!.numberOfSections - 1
// Then grab the number of rows in the last section
let lastRowIndex = self.tableView!.numberOfRows(inSection: lastSectionIndex) - 1
// Now just construct the index path
let pathToLastRow = NSIndexPath(row: lastRowIndex, section: lastSectionIndex)
// Make the last row visible
self.tableView?.scrollToRow(at: pathToLastRow as IndexPath, at: UITableViewScrollPosition.bottom, animated: true)
}
}
The messages are laoded properly and the view does scroll to the last tableViewCell as intended....BUT...I want the view to already appear at that last cell. Along with the three app examples, I've seen other apps do the same thing.
Any help would be greatly appreciated
EDIT: 3:26pm November 17
I've also tried putting the moveToLastComment()
function call in viewDidLoad
after the reloadData()
, viewWillAppear
and viewDidAppear
. No change. In fact, when I put it anywhere other than viewDidAppear
, absolutely nothing happens. I have to scroll down as usual