【问题标题】:prevent table view to scrolling top after insertRows在 insertRows 之后防止表格视图滚动到顶部
【发布时间】: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 会滚动到顶部然后回到表的末尾,这不是好的用户体验。你听懂了吗?

标签: ios swift tableview


【解决方案1】:

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

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

    scrollView.setContentOffset(bottomOffset, animated: true)

【讨论】:

  • 我认为这不是完整的解决方案。
  • 谢谢。我更新了我的代码并使用一些额外的代码添加了您的代码。它现在正在工作。谢谢
  • 也许您可以分享您的解决方案?或者,如果 Tushar 的答案是正确的,接受这个答案吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 2012-09-29
  • 2021-10-24
  • 1970-01-01
  • 2013-02-21
相关资源
最近更新 更多