Swift animate UITableViewCell expanding height constraint [duplicate]
Asked Answered
O

2

6

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
}
Obtest answered 18/2, 2018 at 17:48 Comment(1)
what actually you tring to do? Do you have expand collapse tableview or there is an another concept?Sorenson
V
7

Try without an animation block:

containerHeightConstraint.constant = 410
tableView.beginUpdates()
tableView.endUpdates()
Voluble answered 18/2, 2018 at 17:55 Comment(0)
A
6

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

Anatomize answered 18/2, 2018 at 18:2 Comment(1)
Just to add, UITableView.RowAnimation.automatic can have weird effects on the cell being expanded. If you use UITableView.RowAnimation.none instead, it will be animated and will behave normally. Very strange!Chur

© 2022 - 2024 — McMap. All rights reserved.