3

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)
    }
}
  • Are you sure you are not calling [tableView reloadData] ? Anyway you can use [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; for scrolling to the newly added row – user3752049 Feb 13 '17 at 14:32
  • Hi @user3752049 sure I use scrollToRow...., but the problem was that when I have a big number of rows (ex 50 rows). so when inserting new rows the tableView will scroll to top then back to the end of the table, And this is not good UX. did you understand me? –  Feb 13 '17 at 15:07

2 Answers2

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)
Tushar Sharma
  • 2,839
  • 1
  • 16
  • 38
0

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

Wahab Khan Jadon
  • 875
  • 13
  • 21