OGeek|极客世界-中国程序员成长平台

标题: ios - 在 insertRows 之后防止表格 View 滚动到顶部 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:56
标题: ios - 在 insertRows 之后防止表格 View 滚动到顶部

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



Best Answer-推荐答案


在您的 scrollViewDidScroll 方法中尝试此方法-:

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

    scrollView.setContentOffset(bottomOffset, animated: true)

关于ios - 在 insertRows 之后防止表格 View 滚动到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42206030/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4