【发布时间】:2017-07-01 13:19:21
【问题描述】:
我有viewController,里面有tableView。 这个 tableView 有很多部分和行。 当我尝试在最后一部分中添加新行时,使用 TableView.insertRows(at: [IndexPath(row: r, section: sec)], with: .bottom)
tableView 滚动到顶部,并显示当前部分的第一个单元格。
如何防止tableView滚动到顶部?
谢谢
这是我的解决方案
当尝试添加单元格时,我使用此代码
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)
}
}
【问题讨论】:
-
你确定你没有调用 [tableView reloadData] 吗?无论如何,您可以使用 [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];用于滚动到新添加的行
-
嗨@user3752049 确定我使用scrollToRow ....,但问题是当我有大量行(例如50行)时。所以当插入新行时,tableView 会滚动到顶部然后回到表的末尾,这不是好的用户体验。你听懂了吗?