Easy Expanding/Collapsing TableViewCells

I noticed when using an app the other day that its UITableViewCells were increasing in size when touched, with the height increase also animated. I thought this would be quite difficult to achieve but after digging around it turns out that its quite simple. By the end of this quick post we will have something like the below.

Start by creating a new single view project in Swift. Navigate to the storyboard view and change the default UIViewController for a UITableViewController. Then create a new prototype cell that is 140 points in height. Place the label you want visible when the cell is small in height (44 points) and then place some labels and buttons below. The latter views will be visible when the cell has been touched.

Create a new class called TableViewController and paste the code beneath inside it.

import UIKit

class TableVIewController: UITableViewController { 
    var selectedCellIndex = -1 
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
        return tableView.dequeueReusableCellWithIdentifier("Cell")! 
    } 
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
        return (indexPath.row == selectedCellIndex) ? 140 : 44 
    } override 
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
        selectedCellIndex = (selectedCellIndex == indexPath.row) ? -1 : indexPath.row
        self.tableView.beginUpdates() self.tableView.endUpdates() 
    } 
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
        return 4 
    } 
}

Add the new TableViewController to the UITableViewController in the Storyboard using the Identity Inspector and hit run. Select a row and its size should increase with a nice animation. So how does this work?

BeginUpdates and endUpdates allows you to make changes to the tableView, such as inserting and deleting rows without needing to call for a reload. To make this process look nicer to the user it is animated. Although we don't perform any insertions/deletions between beginUpdates and endUpdates the animation is still triggered as well as heightForRow, where we set the new height of the selected row.

If you don't want the animation to happen just do this

UIView.setAnimationsEnabled(false) self.tableView.beginUpdates() self.tableView.endUpdates() UIView.setAnimationsEnabled(true)