当从一个 View Controller 传递到另一个 View Controller (例如 Instagram 或 Facebook)时,我试图保留 TableView 中单元格的当前 IndexPath.row 。每次我从一个 View Controller 移动到另一个 View Controller 时,我都必须为 TableView 调用 reloadData() 将其加载回来。但是当我这样做时,在进入新的 View Controller 之前我会失去当前位置。
我可以通过在 Controller 之间传递当前的 IndexPath.row 来让它在 didSelect 上工作,但如果用户只是滚动,那么尝试这样做就会变得很麻烦。
如有任何建议,我们将不胜感激!非常感谢!
最佳答案
默认情况下,reloadData
保留contentOffset
。不过,如果您的 estimatedRowHeight
值确实不准确,则可以对其进行更新。
在tableView
上调用reloadData
不会改变内容偏移量。但是,如果您使用的是 iOS 13 中引入的 UITableViewAutomaticDimension
,则可能会遇到问题。
使用UITableViewAutomaticDimension
时,需要编写委托(delegate)方法tableView:estimatedHeightForRowAtIndexPath:
并返回UITableViewAutomaticDimension
以及tableView:heightForRowAtIndexPath :
也返回相同的结果。
对我来说,我在使用 iOS 13 时遇到了问题。这是因为即使我使用 UITableViewAutomaticDimension
,estimatedHeightForRowAtIndexPath:
方法也返回不准确的值。这是 iOS 13 的问题,因为 iOS 13 设备没有问题。
我通过使用字典
来存储单元格高度的值并返回它来解决这个问题。这就是我所做的。
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSNumber *key = @(indexPath.row);
NSNumber *height = @(cell.frame.size.height);
[self.cellHeightsDictionary setObject:height forKey:key];
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSNumber *key = @(indexPath.row);
NSNumber *height = [self.cellHeightsDictionary objectForKey:key];
if (height)
{
return height.doubleValue;
}
return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewAutomaticDimension;
}
关于swift - 当从一个 View Controller 转到另一个 View Controller (例如 Swift 中的 Instagram 或 Facebook)时,如何在 TableView 中保留当前的 IndexPath.row?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59579398/