UITableView jumps after calling reloadSections: withRowAnimation:

I need to expand / collapse the section UITableView. I do this by calling reloadSections:withRowAnimation:and returning 0from tableView:numberOfRowsInSection:if the section should be collapsed.

It works fine, except in one case. If the table view scrolls to the end, and the size of the content decreases after the crash, it ends with scrolling beyond the maximum offset. Now instead of scrolling in place with the animation, it just clicks there, which looks ugly:

enter image description here

Here is what I tried:

  • Wrap reloadSections:withRowAnimation:in beginUpdates/ endUpdates:

    tableView.beginUpdates()
    tableView.reloadSections(indexSet, withRowAnimation: .Automatic)
    tableView.endUpdates()
    

    It did not help.

  • Wrap reloadSections:withRowAnimation:in CATransactionwith a completion block, calculate the scroll distance inside it, and scroll the animation table:

    CATransaction.begin()
    CATransaction.setCompletionBlock {
        // tableView.contentSize is incorrect at this point
        let newContentOffset = ... // calculated value is not correct
        tableView.setContentOffset(newContentOffset, animated: true)
    }
    
    tableView.beginUpdates()
    tableView.reloadSections(indexSet, withRowAnimation: .Automatic)
    tableView.endUpdates()
    CATransaction.commit()
    

, ?

+4
1

. , .

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat 
0

Source: https://habr.com/ru/post/1625336/


All Articles