防止表视图在insertRows之后滚动到顶部 [英] prevent table view to scrolling top after insertRows

查看:139
本文介绍了防止表视图在insertRows之后滚动到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带tableView的viewController. 此tableView有许多节和行. 当我尝试在最后一节中使用添加新行时 TableView.insertRows(at:[IndexPath(row:r,section:sec)],带有:.bottom)

I have viewController with tableView inside it. this tableView has many sections and rows. when I try to add a new row in the last section using TableView.insertRows(at: [IndexPath(row: r, section: sec)], with: .bottom)

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

tableView scrolls to top, and displays the first cell in the current section.

如何防止tableView滚动到顶部?

how to prevent tableView from scrolling to the top?

谢谢

这是我的解决方法

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

When try to add cell, I use this code

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方法中尝试此方法:

Try THIS IN YOUR scrollViewDidScroll METHOD-:

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

    scrollView.setContentOffset(bottomOffset, animated: true)

这篇关于防止表视图在insertRows之后滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆