UITableView内容大小何时用行插入/删除animation更新?

我很好奇,当插入/删除animation调用后,UITableView的内容大小更新。 我想这将是像大多数[UIViewanimation…]块,即使animation未完成,帧大小/内容大小将立即更新,但似乎并不是这样。 有任何想法吗?

不幸的是,我还没有find一个更好的方式来更新contentSize从UITableView添加/删除行,但我find了一种方法来计算将是如果你知道你是单元格的索引path添加/移除。

使用已修改行的索引path,可以使用tableView:heightForRowAtIndexPath:方法计算各个单元格的高度,并将其添加到表视图的当前内容大小高度。 下面是一个例子,如果你只添加一行:

[self.tableView insertRowsAtIndexPaths:@[indexPathOfNewRow] withRowAnimation:UITableViewRowAnimationAutomatic]; CGFloat newCellHeight = [self tableView:self.tableView heightForRowAtIndexPath:indexPathOfNewRow]; CGFloat newContentSizeHeight = self.tableView.contentSize.height + newCellHeight 

调用代表高度后,内容大小将发生变化:

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section; - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section; 

它看起来像sizeThatFits()可以公开一个新的contentSize的高度悬而未决。 然后,您可以分配该待处理的大小,以便及早解决滚动animation。

有了这样的事情:

 extension UIScrollView { var pendingContentSize: CGSize { var tallSize = contentSize tallSize.height = .greatestFiniteMagnitude return sizeThatFits(tallSize) } func scrollToBottom(animated: Bool) { contentSize = pendingContentSize let contentRect = CGRect(origin: .zero, size: contentSize) let (bottomSlice, _) = contentRect.divided(atDistance: 1, from: .maxYEdge) guard !bottomSlice.isEmpty else { return } scrollRectToVisible(bottomSlice, animated: animated) } } 

我能够写这样的视图控制器代码:

 tableView.insertRows(at: [newIndexPath], with: .none) tableView.scrollToBottom(animated: true) 

并使表滚动到底部(使用新的内容大小),而不是滚动到倒数第二行(使用旧的内容大小)。