Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView jumps after calling reloadSections:withRowAnimation: [duplicate]

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

It works fine except for one case. If the table view is scrolled all the way down and content size decreases after collapse, it ends up being scrolled beyond maximum offset. Now instead of scrolling in place with animation it just snaps there, which looks ugly:

enter image description here

Here's what I have tried:

  1. Wrapping reloadSections:withRowAnimation: in beginUpdates/endUpdates:

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

    That did not help.

  2. Wrapping reloadSections:withRowAnimation: in CATransaction with completion block, calculating the scroll distance within it and scrolling table view with animation:

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

How do I make sure the table view does not jump?

like image 956
Andrii Chernenko Avatar asked Jan 21 '16 13:01

Andrii Chernenko


1 Answers

I ran into this issue when using custom headers in collapsible sections. I did solve it by implementing.

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat 
like image 200
Hugo Perez Avatar answered Sep 22 '22 14:09

Hugo Perez