Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

1 Answers

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)
like image 71
Tushar Sharma Avatar answered May 27 '26 19:05

Tushar Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!