I have viewController with tableView inside it. this tableView has many sections and rows. when I try to add a new row in the last section using TableView.insertRows(at: [IndexPath(row: r, section: sec)], with: .bottom)
tableView scrolls to top, and displays the first cell in the current section.
how to prevent tableView from scrolling to the top?
thanks
This my solution
When try to add cell, I use this code
self.didAddNewCell = true
self.chatTableView.reloadData()
self.scrollToBottom()
Then adding this code
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if self.didAddNewCell {
self.didAddNewCell = false
let bottomOffset = CGPoint(x: CGFloat(0), y:CGFloat(chatTableView.contentSize.height - self.chatTableView.bounds.size.height))
scrollView.setContentOffset(bottomOffset, animated: true)
}
}
And this code for scrolling to bottom
func scrollToBottom() {
let sections = self.chatTableView.numberOfSections
if sections > 0 {
let rows = self.chatTableView.numberOfRows(inSection: sections - 1)
let last = IndexPath(row: rows - 1, section: sections - 1)
self.chatTableView.scrollToRow(at: last, at: .none, animated: false)
}
}