Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift animate UITableViewCell expanding height constraint [duplicate]

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
}
like image 652
Niall Kiddle Avatar asked Feb 18 '18 17:02

Niall Kiddle


2 Answers

Try without an animation block:

containerHeightConstraint.constant = 410
tableView.beginUpdates()
tableView.endUpdates()
like image 66
André Slotta Avatar answered Oct 19 '22 16:10

André Slotta


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

like image 32
Sid Mhatre Avatar answered Oct 19 '22 16:10

Sid Mhatre