Write better static UITableView with Swift 5 programmatically

Kevin Laminto
3 min readAug 7, 2020

--

Photo by Toa Heftiba on Unsplash

Let’s face it, tableview is not going anywhere within the next few years. It’s such a classic way to display a group of similar datas.

So in this article, I will make sure to keep it concise on how to programatically create a static UITableView for those who does not want to implement it via the storyboard (for consistency reason, or whatever you want).

We will implement a MVVM architecture with this project, so that we can keep it clear and further promote encapsulation. We will also try and make a settings view because that’s one of the perfect example on static UITableView.

Step 1

Create your UITableViewController class.

You also want to create a new file called SettingsViewModel. This class will be in charge of the delegates and datasource for the tableview. Also, protocol to pass to the main VC, this case, the UITableViewController class.

Note that SettingsViewModelDelegate is optional (not code optional, just depends with you). If you want the whole handling to be located inside the ViewModel, it’s totally doable. So instead having a delegate, you call a local function.

Step 2

Now let’s fill in our ViewModel class. We need to create two model objects. One for the Section, and the other for the item within that section.

We will call them SettingsSection and SettingsItem respectively. You can either add it to the ViewModel class, or create a new file. Up to you.

For this article, we will keep it simple. A simple section with a title (no footer).

Step 3

Now that our setup is complete, let’s fill in the datasource! on your ViewModel class, go ahead and fill the configureDatasource() method like so

And our tableview delegations and datasource

Nothing special, just your normal tableview delegates and datasource methods. Look at how simple and clean it is! Rather than using the switch case approach.

Step 4

Now that we are done with our ViewModel, let’s head to the main class and fill in the rest. And you’re done!

Here is the UI result of the settings I created for my open-source project.

Conclusion

Now this is not the one and only best way of creating it, but in my use case, it’s good enough, and thought that I could share it as well. If you are interested in seeing the full working code that uses this approach, I have an open-source project available on github here.

If you have any questions or improvements, feel free to email me at kevin.laminto@gmail.com or dm me on twitter!

--

--