有没有办法让 UITableView 的估计行高实际上与准确的滚动位置一起工作?

Posted

技术标签:

【中文标题】有没有办法让 UITableView 的估计行高实际上与准确的滚动位置一起工作?【英文标题】:Is there a way to make estimated row heights with UITableView actually work with accurate scroll position? 【发布时间】:2014-12-29 06:43:59 【问题描述】:

使用UITableView 估算的行高对性能很有帮助,但是当您尝试使用您的表格视图获得准确的滚动偏移时,它们会令人头疼。

This article from Ray Wenderlich 在底部详细说明了一些问题。 As does this article。当您转到一个新的视图控制器然后返回到表格视图时,表格视图会完全混淆您的位置,并且不会将用户返回到他们以前的位置。有时旋转甚至简单的滚动也会发生同样的情况。

我不禁想知道...... 那有什么意义?它不应该把你带回到你以前的确切位置吗?

我知道估计很难,但除了给出 完美 估计(这不是真正的估计并破坏目的)之外,没有其他方法可以实现吗?因为现在除非有一个带有单元格的视图控制器,否则任何其他情况,例如切换到新的视图控制器似乎真的搞砸了。

我如何以一种真正有用且不会导致到处乱跳的方式使用估算值?

【问题讨论】:

【参考方案1】:

我遇到了与您完全相同的问题 - UIPageViewController 中嵌入了不同行高的 UITableView。 TableView 可以很好地滚动,我会滑开并回到桌子上,位置就会到处都是。

同时使用estimatedHeightForRowAtIndexPath 和heightForRowAtIndexPath 是我的诀窍,如this article 所示。从那时起,每当我滑开并回到桌子上时,位置都会保持不变。万岁!

但仍然存在问题:第一次加载表格时,estimatedRowHeights 只获取单元格的后半部分(例如,32 个单元格中的第 16 到 31 行),因此让您开始在中间。只要我滚动,前半部分单元格(第 0 到 15 行)就会加载,我会回到第 0 行而不是第 15 行。之后表格会正常运行。

虽然是一个小问题,但解决方法是在最后一个单元格加载后模拟向上滚动。这会触发第一个单元格的加载,并将您的表格带到“正确”的第 0 行。

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
    // return whatever the cell height should be
    return myCellsArray[indexPath.row]["height"] as CGFloat


func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
    // return whatever the cell height should be
    return myCellsArray[indexPath.row]["height"] as CGFloat


func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) 

    // Check that the final cell has been loaded and that this is the first time the table is loaded
    if indexPath.row == myCellsArray.count - 1 && myStruct.tableHasLoaded == false
        // Reached the bottom
        println("bottom reached with cell \(indexPath.row)")
        // Simulate a mini scroll backwards as estimatedRowHeight only starts halfway and loads the final half, not the first half of the cells
        // This way it forces it to go back to row 0
        self.setContentOffset(CGPoint(x: 0, y: -1), animated: false)
        // Set bool to true - we don't want to go back to the top everytime we reach the bottom of the table
        myStruct.tableHasLoaded = true
    

【讨论】:

以上是关于有没有办法让 UITableView 的估计行高实际上与准确的滚动位置一起工作?的主要内容,如果未能解决你的问题,请参考以下文章

UITableView 估计行高动态类型

如何让 UITableView 行高自动调整为 UITableViewCell 的大小?

如何在不指定估计行高的情况下使用 iOS 自动调整单元格大小?

获取 UITableView Swift 中每一行的 RowHeight

使用估计的HeightForRowAtIndexPath 错误的滚动位置

通用故事板 UITableview 行高