【问题标题】:How to let UITableView scroll to the bottom in dynamic height cells?如何让 UITableView 在动态高度单元格中滚动到底部?
【发布时间】:2018-01-04 06:30:42
【问题描述】:

我有一个包含许多单元格的 UITableView。
其内容后面的每个单元格都有动态高度。
但是我注意到当我进入这个 viewController 时,UITableView 有时不会滚动最后一个 indexPath。
有任何想法来解决它。

tableView.estimatedRowHeight = 200.0
tableView.rowHeight = UITableViewAutomaticDimension

let bottomOffSet = CGPoint(x: 0, y: self.tableView.contentSize.height - self.tableView.bounds.size.height)
self.tableView.setContentOffset(bottomOffSet, animated: false)

PS:我不想使用“scrollToRow”,因为它会比“setContentOffset”多次触发 tableview 的函数“cellForRowAtIndexPath”。

tableView.scrollToRow(at: IndexPath(row: contents.count - 1, section: 0), at: .top, animated: animated)

【问题讨论】:

  • 我不明白如何设置tableView's contentOffset 将滚动到最后一个索引路径?你到底想达到什么目的。
  • @PGDev 就像一个聊天应用的聊天视图,我想滚动到最新消息。
  • 你为什么不简单地使用scrollToRow(at indexPath: IndexPath, at scrollPosition: UITableViewScrollPosition, animated: Bool)?这是实现这一目标的直接方式。是的,cellForRowAtIndexPath 会因为tableViewCell's 的可重用性而被多次调用,如果单元格尚不可见。每当重用单元格时,都会在每种情况下调用它。

标签: ios swift tableview


【解决方案1】:

尝试将tableView's contentOffset 设置为tableView's contentSize,即

override func viewDidAppear(_ animated: Bool)
{
    super.viewDidAppear(animated)
    let bottomOffSet = CGPoint(x: 0, y: self.tableView.contentSize.height - self.tableView.bounds.size.height)
    self.tableView.setContentOffset(bottomOffSet, animated: false)
}

在viewDidAppear 中设置contentOffset。

同时实现以下UITableViewDelegate 方法:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
    return UITableViewAutomaticDimension
}

override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat
{
    return 126.0 //Maximum possible cell height
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    相关资源
    最近更新 更多