ios - 防止 TableView 在 insertRows 后滚动到顶部

标签 ios swift tableview

我有一个带有 tableView 的 viewController。 这个 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)
    }
}

最佳答案

在您的 scrollViewDidScroll 方法中试试这个:

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

    scrollView.setContentOffset(bottomOffset, animated: true)

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

相关文章:

ios - 表格 View 中选择和取消选择单元格之间的差异

ios - 如何使堆栈 View 或容器 View 包装内容?

swift - 在自定义 tableView 单元格上使用 contentView 属性(作为标题传递)如何防止它使自定义属性无效?

ios - 使用 UIImageView 设置缩放 UIScrollView

ios - 使用大量内存的动画iOS7

ios - 什么时候进行ios自动屏幕捕获?

swift - becomeFirstResponder 和 estimatedRowHeight 不兼容

ios - 如何在 swift 中的 do 函数中为字符串添加 +1 以进行分页

ios - 存储不同 NSData 时 Realm 文件大小差异过大

iphone - 如何自定义 iOS 警报 View ?