当重新加载具有不断变化的单元格高度的单元格时,UITableView会滚动到顶部

我有一个表视图,它包含一个占位符,当它加载到图像中。 加载图像时,我调用reloadRowsAtIndexPaths:withRowAnimation: . 此时,单元格会根据图像的大小更改高度。 当发生这种情况时,我希望表格视图的内容偏移保持在原位,并且如下图所示,可以将下面的单元格进一步向下推动。

我得到的效果是滚动视图滚动回到顶部。 我不确定为什么会这样,我似乎无法阻止它。 在reloadRows行之后放置beginUpdates()endUpdates()无效。

我正在使用estimatedRowHeight ,因为我的表视图可能有数百行不同的高度。 我也在实现tableView:heightForRowAtIndexPath: .

编辑:我已经设置了一个演示项目来测试这个,并且无可否认我无法获得演示项目来重现这种效果。 我会继续努力。

始终更新主线程上的UI。 所以只是放置

 [self.tableView reloadData]; 

在主线程内:

 dispatch_async(dispatch_get_main_queue(), ^{ //UI Updating code here. [self.tableView reloadData]; }); 

这是estimatedRowHeight的一个问题。

estimatedRowHeight与实际高度的差异越大,表格在重新加载时可能跳得越多,尤其是滚动得越远。 这是因为表格的估计大小与其实际大小完全不同,迫使表格调整其内容大小和偏移量。

最简单的解决方法是使用非常准确的估算。 如果每行的高度变化很大,请确定行的中间高度,并将其用作估计值。

我遇到了同样的问题,并通过这种方式决定:在加载时保存单元格的高度,并在tableView:estimatedHeightForRowAtIndexPath给出准确的值tableView:estimatedHeightForRowAtIndexPath

 // declare cellHeightsDictionary NSMutableDictionary *cellHeightsDictionary; // save height - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { [cellHeightsDictionary setObject:@(cell.frame.size.height) forKey:indexPath]; } // give exact height value - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath { NSNumber *height = [cellHeightsDictionary objectForKey:indexPath]; if (height) return height.doubleValue; return UITableViewAutomaticDimension; } 

我看到了这个,而对我有用的修复方法是选择估计的行高,这是可能行中最小的行。 当非预期的滚动发生时,它最初被设置为最大可能的行高。 我只是使用单个tableView.estimatedRowHeight属性,而不是委托方法。

Interesting Posts