'prevent table view to scrolling top after insertRows

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


Solution 1:[1]

Try THIS IN YOUR scrollViewDidScroll METHOD-:

  CGPoint bottomOffset = CGPoint(x: CGFloat(0), y:CGFloat(scrollView.contentSize.height - self.scrollView.bounds.size.height))      

    scrollView.setContentOffset(bottomOffset, animated: true)

Solution 2:[2]

updating the @Tushar Sharma answer...

just put the following line in method scrollViewDidScroll in your UITableView...

contentOffset = CGPoint(x: CGFloat(0), y:CGFloat(scrollView.contentSize.height - scrollView.bounds.size.height))

where the contentOffset is CGPoint... declear the global variable of contentOffset..

var contentOffset : CGPoint?

and use contentOffset value written after the code which causes the UITableView to scroll to the top as follow...

self.tableView.setContentOffset(self.contentOffset!, animated: false)

in my case its was self.tableView.reloadData() because i append values in dataset at index 0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tushar Sharma
Solution 2 Wahab Khan Jadon