防止插入行后表格视图滚动到顶部

3
我有一个包含 tableView 的 viewController。 tableView 中有很多的 section 和 row。 当我尝试在最后一个 section 中添加新行时,使用 TableView.insertRows(at: [IndexPath(row: r, section: sec)], with: .bottom)。
tableView 滚动到顶部,并显示当前 section 的第一个单元格。
如何防止 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
嗨@user3752049,我确实使用了scrollToRow...,但问题是当我有大量行(例如50行)时。因此,在插入新行时,tableView将滚动到顶部,然后返回到表的末尾,这不是良好的用户体验。你明白我的意思吗? - user515060
2个回答

1
尝试在你的scrollViewDidScroll方法中加入以下内容:
  CGPoint bottomOffset = CGPoint(x: CGFloat(0), y:CGFloat(scrollView.contentSize.height - self.scrollView.bounds.size.height))      

    scrollView.setContentOffset(bottomOffset, animated: true)

我认为这不是完整的解决方案。 - user515060
谢谢。我更新了我的代码,并加入了你的代码和一些额外的代码。现在它可以工作了。谢谢。 - user515060
也许你可以分享一下你的解决方案?或者,如果Tushar的回答是正确的话,接受这个答案? - Reinhard Männer

0

更新@Tushar Sharma的答案...

只需将以下行放入您的UITableView中的scrollViewDidScroll方法中...

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

其中contentOffsetCGPoint... 声明全局变量contentOffset..

var contentOffset : CGPoint?

并在导致UITableView滚动到顶部的代码后使用contentOffset值,如下所示...

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

在我的情况下,它是self.tableView.reloadData(),因为我在索引0处附加了数据集的值


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接