Swift: How to animate rowHeight UITableView?

I am trying to animate the height of tables with tableViewCell by calling startAnimation () inside the tableView function:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! TableViewCell tableView.rowHeight = 44.0 startAnimation(tableView) return cell } //MARK: Animation function func startAnimation(tableView: UITableView) { UIView.animateWithDuration(0.7, delay: 1.0, options: .CurveEaseOut, animations: { tableView.rowHeight = 88.0 }, completion: { finished in print("Row heights changed!") }) } 

Result: line height changes, but without any animation. I do not understand why the animation does not work. Should I possibly identify some initial and final state?

+14
source share
2 answers

Do not change the height in this way. Instead, when you know you want to change the height of the cell, call (in any function):

 self.tableView.beginUpdates() self.tableView.endUpdates() 

These calls notify the tableView to check for height changes. Then do the delegate override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat and specify the correct height for each cell. The change in height will be animated automatically. You can return UITableViewAutomaticDimension for elements that do not have an explicit height for.

I would not suggest doing such actions from cellForRowAtIndexPath , however, but in one that responds, for example, by pressing didSelectRowAtIndexPath . In one of my classes, I:

 override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath == self.selectedIndexPath { self.selectedIndexPath = nil }else{ self.selectedIndexPath = indexPath } } internal var selectedIndexPath: NSIndexPath? { didSet{ //(own internal logic removed) //these magical lines tell the tableview something up, and it checks cell heights and animates changes self.tableView.beginUpdates() self.tableView.endUpdates() } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath == self.selectedIndexPath { let size = //your custom size return size }else{ return UITableViewAutomaticDimension } } 
+22
source
 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! TableViewCell tableView.rowHeight = 44.0 UIView.animateWithDuration(0.7, delay: 1.0, options: .CurveEaseOut, animations: { tableView.rowHeight = 88.0 cell.layoutIfNeeded() }, completion: { finished in print("Row heights changed!") }) return cell } 
+1
source

All Articles