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:
Here's what I have tried:
Wrapping reloadSections:withRowAnimation:
in beginUpdates
/endUpdates
:
tableView.beginUpdates()
tableView.reloadSections(indexSet, withRowAnimation: .Automatic)
tableView.endUpdates()
That did not help.
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With