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

And*_*rew 9 objective-c uitableview ios

我有一个表视图,它包含一个占位符,当它加载到图像中.加载图像后,我打电话reloadRowsAtIndexPaths:withRowAnimation:.此时,单元格会根据图像的大小更改高度.当发生这种情况时,我希望表视图的内容偏移保持在原位,并且下面的单元格可以进一步向下推,就像您想象的那样.

我得到的效果是滚动视图滚动回到顶部.我不知道为什么会这样,我似乎无法阻止它.把beginUpdates()前和endUpdates()reloadRows线没有任何影响.

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

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

小智 28

这是estimatedRowHeight的一个问题.

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

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


Bai*_*aig 10

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

[self.tableView reloadData];
Run Code Online (Sandbox Code Playgroud)

在主线程内:

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


Igo*_*gor 6

我遇到了同样的问题并通过这种方式决定:在加载时保存单元格的高度并给出准确的值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;
}
Run Code Online (Sandbox Code Playgroud)