9

I am curious when the UITableView's content size is updated after doing an insert/delete animation call. I figured it would be like most [UIView animation...] blocks in that the frame size/content size would be updated immediately even though the animation hasnt completed, but it does not seem to be that way. Any ideas?

4

3 回答 3

3

不幸的是,在从 UITableView 添加/删除行时,我也找不到更新 contentSize 的好方法,但我确实找到了一种方法来计算如果你知道你所在的单元格的索引路径会是什么添加/删除。

使用修改后的行的索引路径,您可以使用 tableView:heightForRowAtIndexPath: 方法计算各个单元格的高度,并将其添加到表格视图的当前内容大小高度。如果您只添加一行,这是一个示例:

[self.tableView insertRowsAtIndexPaths:@[indexPathOfNewRow] withRowAnimation:UITableViewRowAnimationAutomatic];
CGFloat newCellHeight = [self tableView:self.tableView heightForRowAtIndexPath:indexPathOfNewRow];
CGFloat newContentSizeHeight = self.tableView.contentSize.height + newCellHeight
于 2013-09-06T19:19:47.787 回答
2

看起来可以暴露一个待处理sizeThatFits()的新的高度。contentSize然后,您可以分配该挂起的大小以使其尽早解决滚动动画。

像这样:

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)

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

于 2017-01-11T01:42:08.197 回答
0

调用委托关于高度后,内容大小将发生变化:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
于 2013-07-13T23:58:20.373 回答