本文介绍了具有动态单元格高度的UITableView的reloadData()导致跳跃式滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得这可能是一个常见的问题,并且想知道是否有任何通用的解决方案.

I feel like this might be a common issue and was wondering if there was any common solution to it.

基本上,我的UITableView具有每个单元格的动态单元格高度.如果我不在UITableView的顶部并且我tableView.reloadData(),则向上滚动会变得跳动.

Basically, my UITableView has dynamic cell heights for every cell. If I am not at the top of the UITableView and I tableView.reloadData(), scrolling up becomes jumpy.

我认为这是由于以下事实:当我向上滚动时重新加载数据时,UITableView正在重新计算每个可见单元的高度.如何缓解这种情况,或者如何仅将数据从某个IndexPath重载到UITableView的末尾?

I believe this is due to the fact that because I reloaded data, as I'm scrolling up, the UITableView is recalculating the height for each cell coming into visibility. How do I mitigate that, or how do I only reloadData from a certain IndexPath to the end of the UITableView?

此外,当我设法一直滚动到顶部时,我可以先向下再向上滚动,没有跳跃的问题.这很可能是因为已经计算了UITableViewCell的高度.

Further, when I do manage to scroll all the way to the top, I can scroll back down and then up, no problem with no jumping. This is most likely because the UITableViewCell heights were already calculated.

推荐答案

为防止跳跃,应在单元格加载时保存它们的高度,并在tableView:estimatedHeightForRowAtIndexPath中给出确切的值:

To prevent jumping you should save heights of cells when they loads and give exact value in tableView:estimatedHeightForRowAtIndexPath:

迅速:

var cellHeights = [IndexPath: CGFloat]()

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cellHeights[indexPath] = cell.frame.size.height
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return cellHeights[indexPath] ?? UITableView.automaticDimension
}

目标C:

// declare cellHeightsDictionary
NSMutableDictionary *cellHeightsDictionary = @{}.mutableCopy;

// declare table dynamic row height and create correct constraints in cells
tableView.rowHeight = UITableViewAutomaticDimension;

// 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;
}

这篇关于具有动态单元格高度的UITableView的reloadData()导致跳跃式滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 10:40