Dynamic screen content made with Table Section Modules in Swift

Kerim Njuhovic
2 min readDec 30, 2020

Well, you are probably tired of seeing in your project many implementations of the two protocols: UITableViewDelegate & UITableViewDataSource. What about having only single implementation of the previously mentioned protocols?

The main idea is to have a screen on iOS Device composed out of modules which you can easily add them, remove them and get bonus auto resize of the screen content. A Module in the implementation is related to a Section in a UITableView which should be able to work for itself independently. Thus, as result in your UIViewController you are dealing with the Modules and its data types, on the other side you are leaving to Module to deal with the low level things such as UITableViewCell and table view protocols implementation stuff.

Let’s dive deep

Table Section Module

The heart of the implementation idea represents the class which will implement UITableViewDelegate & UITableViewDataSource. In addition, the class will have initialiser dependency injection on the main table view property from your UIViewController.
For now it will be omitted but in your TableSectionModule you can add various types of boilerplate code related to the table view: code for calculation for needed height and resizing of cells in case you add or remove module, auto register cells and so on. The rough implementation looks like following:

Sample Module

Now, lets use the previously created TableSectionModule. We will create our sample module which will inherit from TableSectionModule and override what is needed.

Let’s glue it all together

In the ViewController where the table view reference is located we can simply append the modules to the table view. No more UITableViewDelegate and UITableViewDataSource boilerplate code 💫.

And now, final result:

let sampleModule = SampleModule(tableView: self.baseTableView!) 
self.appendModule(firstModule)

There already exists some ready solutions published as Third Party libraries to be integrated via CocoaPods. Some of them are TableSectionModules and FTMTableSectionModule. In essence, they are all implementation of the idea published in this article with some difference based on boilerplate code extracted. Now, it is up to you whether you have time for custom implementation or easy integration of existing library.

Happy Coding 🍀

--

--