阻止表视图在insertRows之后滚动顶部

里面有tableView的viewController。 这个tableView有很多部分和行。 当我尝试使用TableView.insertRows(在:[IndexPath(row:r,section:sec)],在:最后一节添加一个新行:.bottom)

tableView滚动到顶部,并显示当前部分中的第一个单元格。

如何防止tableView滚动到顶部?

谢谢


这是我的解决scheme

当尝试添加单元格时,我使用此代码

self.didAddNewCell = true self.chatTableView.reloadData() self.scrollToBottom() 

然后添加这个代码

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

而这个代码滚动到底部

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

试试这个在你的scrollViewDidScroll方法:

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