When does UITableView content size update with row insert/delete animation

前端 未结 3 1736
情书的邮戳
情书的邮戳 2021-01-12 02:08

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 tha

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-12 02:31

    It looks like sizeThatFits() can expose the height of a new contentSize that's pending. You can then assign that pending size to have it resolve early for scroll animations.

    With something like this:

    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)
        }
    
    }
    

    I'm able to write view controller code like this:

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

    and have the table scroll all the way to the bottom (using the new content size) instead of it scrolling down to the 2nd-to-last row (using the old content size).

提交回复
热议问题