UITableView with collapsible sections

Today I want to demonstrate a simple way to implement a UITableView with sections which can be collapsed/expanded. At the very end of the post you’ll see the link for the complete Xcode project.
Firstly, I was trying to use UITableViewHeaderFooterView but very soon I realised that I would have write a lot of code and also create and register .xib file which is not fun at all. That’s why I decided to use a trick and replace a header with a simple UITableViewCell subclass.
In the example below I’m gonna use Swift 3. Also I consider that you’re familiar with table views.
At the very beginning let’s add a table view with 2 cell prototypes: one for header and another one for actual content. The controller’s structure in storyboard should look like this:

Here we’ll use a custom cell subclass for our header and basic UITableViewCell for content (actually you can replace it later with whatever you need).
Now it’s time to create a Swift file for our header. It should look something like this:

As you can see, I used 2 images which will help our app users understand if the section is collapsed/expanded. Don’t forget to connect the outlets in storyboard and set header prototype cell class to the one that we’ve just created:

Now it’s time to start coding our ViewController. Firstly, be sure to conform UITableView protocols and set the VC as data source and delegate of the table in storyboard.

After that let’s set constants for cell identifiers and create mock model which will store headers’ titles, their states and number of actual rows in section.

If we have, for example, 4 rows with actual content in a section it means that there will be 5 rows in total (because the first one is always a header cell). If the section is collapsed the user will see only the header of the current section (1 cell):

Now we should tell our table view which cells to dequeue depending on row index in section:

If you launch the app now there will be sections which start with header cells. It’s right what we wanted! The last thing that we haven’t implemented yet is expanding/collapsing behavior. All you need to do is to toggle section state in the array we created at the beginning and to reload the section which was toggled:

That’s all! Now you should be able to collapse/expand your table view sections with nice animation. If it doesn’t work here you can download the complete Xcode project: https://github.com/Legonaftik/CollapsibleTableViewDemo
