Expandable UITableViewCell

Introduction

Implementing an expandable table cell may cause a headache (as a programming at all) In this article we are going to make such cell in a pretty simple way.

Domain

First, we need to define a data to work with. They will be represented by News struct. ViewData class serves a decorator.

https://gist.github.com/trotnic/793b5c99fbb5cf51876b1d07aadc058c

View controller is pretty simple. Acts as a dataSource for tableView, provides data and methods implementations.

Method tableView(_:cellForRowAt:) is the most interesting here. it’s arguments are ViewData object and closure. The latter accepts in parameters another closure, called callback. This closure is configured within cell, what we will see later. And this closure is invoked within performBatchUpdates(_:completion:)method of tableView, what makes the significant part of all the magic with expansion.

https://gist.github.com/trotnic/954b3e25a5e4562fc9f66289e6430846

And now the most important part… cell.

https://gist.github.com/trotnic/ebbe45c971f4cdc8e024717ac94b7241

In the configuration method we save completion, provided by the controller, and set isHidden property of summaryLabel to an appropriate relatively to the current item state.

The stored callback closure is invoked when the expandButtonis clicked. And as a parameter is passed another closure, where the rest part of the whole magic is happening.

First of we toggle the model expansion state. Then within animation method we set within isHidden property of summaryLabel appropriate inverted value of the current model. Inverted because the expanded state means no hidden labels.

Additionally we freeze titleLabel height using constraint for a period of animation. It’s important because titleLabel’s bottom anchor is linked to mainStack’s top and when mainStack recalculates it’s height, this action affects on the titleLabel and makes it to recalculate it’s height too. And to prevent this we freeze height.

And result:

Outro

Hope this article was helpful and you found out to deal your problem. 😃

iOS developer, student