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

标签 ios objective-c uitableview ios7 ios8

使用 UITableView 估算的行高非常适合性能,但是当您尝试使用表格 View 进行准确的滚动偏移时,他们会很头疼。

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

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

我知道估计很难,但是除了给出完美的估计(这不是真正的估计并且违背了目的)之外,没有办法做到这一点吗?因为现在除非有一个带有单元格的 View Controller ,否则任何其他情况,例如切换到一个新的 View Controller 似乎真的把它搞砸了。

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

最佳答案

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

this article 中所示,同时使用 estimatedHeightForRowAtIndexPath 和 heightForRowAtIndexPath 对我来说是诀窍。 .从那时起,每当我滑开并回到 table 上时,位置都会保持不变。欢呼!

但是仍然存在一个问题:第一次加载表时,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
    }
}

关于ios - 有没有办法让 UITableView 的估计行高实际上与准确的滚动位置一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27684525/

相关文章:

ios - 检测贝塞尔曲线路径内的水龙头

iOS7上分组UITableView的标题 View 高度

iphone - 在 Cocos2D 中访问 mp3

ios - UITapGestureRecognizer - 检测双击或三次点击?

ios - 以纵向模式单独显示主视图

ios - 设置代码、 Storyboard 中引用的标签?

ios - UITableview 部分索引点击事件

iphone - 在 UITableView 中显示可下载内容的正确方法(使用 ProgressBar 等)

ios - RestKit 中每个请求的自定义 header

ios - 比较 ios Swift 中的时间