【问题标题】:Scroll to bottom for Table View after Reload Data [duplicate]重新加载数据后滚动到底部以查看表格视图[重复]
【发布时间】:2020-06-18 01:24:39
【问题描述】:

添加 cmets 和回复后,我试图将我的表格视图滚动到底部。评论是部分,回复是该特定部分的行,但在 API 调用添加评论后,表格视图不会在内容的确切底部滚动,我已经尝试了网上所有可能的解决方案。请提出任何相同的解决方案

【问题讨论】:

  • 您能分享一些代码以获得更好的解释吗?你以前尝试过什么?
  • 尝试使用scrollToRow方法

标签: ios swift uitableview uiscrollview sections


【解决方案1】:

这可以通过简单的 TableView 滚动到底部来完成,使用 IndexPath

tblView.scrollToRow(at: IndexPath(row: 8, section: 0), at: .bottom, animated: true)

【讨论】:

  • 很遗憾最后一节没有行
  • 那么你是在展示 cmets 吗?
  • 我正在展示作为 UITableView 部分的 cmets
  • 你有什么部分?标题?
  • 是UITableViewHeaderFooterView,高度是动态的
【解决方案2】:

来自Jayraj Vala的回答

您已将tableViewcontentSize 计算为在任何特定点滚动 使用下面的代码滚动到tableView 的底部。

func scrollToBottom()  {
        let point = CGPoint(x: 0, y: self.tableView.contentSize.height + self.tableView.contentInset.bottom - self.tableView.frame.height)
        if point.y >= 0{
            self.tableView.setContentOffset(point, animated: animate)
        }
  }
  • 当你想滚动tableView时,使用描述的func()

【讨论】:

  • 我还需要补充一点,您应该在调用reloadData() 函数之后调用它,否则它会产生不正确的contentSize 计算
  • 非常感谢您的帮助,但我尝试了上面的代码,但没有解决我的问题
【解决方案3】:

作为UITableView的扩展:

extension UITableView {

    func scrollToBottom(withAnimation animated: Bool = true)  {
        let rowCount = self.numberOfRows(inSection: self.numberOfSections - 1) - 1
        // This ensures we don't scroll to the bottom if there is no content
        guard rowCount > 0 else { return }

        let point = CGPoint(x: 0, y: self.contentSize.height + self.contentInset.bottom - self.bounds.height)
        // This ensures we don't scroll to the bottom if all the content is small enough to be displayed without a scroll
        guard point.y >= 0 else { return }

        self.setContentOffset(point, animated: animated)
    }
}

请务必在tableView.reloadData() 之后调用此函数,否则使用的表格视图contentSize 将不正确。

【讨论】:

  • 很遗憾,最后一节没有行。我想导航到最后一节
  • @UserTech 只需删除rowCount 检查然后。点和滚动代码将起作用
  • 是的,我已经尝试了代码let point = CGPoint(x: 0, y: self.contentSize.height + self.contentInset.bottom - self.bounds.height) // This ensures we don't scroll to the bottom if all the content is small enough to be displayed without a scroll guard point.y >= 0 else { return } self.setContentOffset(point, animated: animated),但不幸的是它对我不起作用
  • @UserTech 而不是self.setContentOffset(point, animated: animated) 你能试试self.contentOffset = point吗?如果仍然无法正常工作,也请尝试拨打self.layoutIfNeeded()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-10
  • 2020-08-09
  • 2021-08-12
  • 1970-01-01
相关资源
最近更新 更多