I have a TableView with a static cell inside which I would like to expand when a button has been pressed. There is a container view inside the cell, the constraints have been set up correctly but I am not sure how to actually animate the cell expanding as it requires me to refresh the table view to update the constraints and expand the cell.
Currently when I call expandContainerView
it doesn't animate, because I am calling self.tableView.reloadData
.
Here is the code that I have used to expand the cell
@objc private func expandContainerView(notification: NSNotification) {
self.view.layoutIfNeeded()
UIView.animate(withDuration: 2.0, delay: 0.0, options: .curveEaseOut, animations: {
self.containerHeightConstraint.constant = 410
self.view.layoutIfNeeded()
self.tableView.reloadData()
}, completion: nil)
}
And here is my height for each row at index code
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
Try without an animation block:
containerHeightConstraint.constant = 410
tableView.beginUpdates()
tableView.endUpdates()
You can only reload cell which you want to expand using below code. I added in the didSelectRowAt
but you can add same code in button action method.
Set expandCell variable to true for changing height of cell when reloading.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Expand View
self.expandCell = true
self.tableView.beginUpdates()
self.tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
self.tableView.endUpdates()
}
You need specify height to expand cell view else it will show default height.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == expandRowIndex && self.expandCell {
return 200
}
return UITableViewAutomaticDimension
}
Note : No need of animation for this. Expansion of view animation at time of reloading cell
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