Creating a settings screen using UITableViewController

A settings screen is a screen that looks something like this:

When I started out with iOS development, I knew only one way of creating such a screen. I would create a UIScrollView and just put all the views and their constraints on it manually using the Interface Builder. That was a lot of work but at that time I didn’t know any better.

Once I had a job interview. And an interviewer asked me how I implemented a certain settings screen in my app. I told him it was a UIScrollView with a bunch of views in it. He asked me why I hadn’t used UITableView, that way I could have  implemented repeating elements as UITableViewCells. Good idea! – I thought.

Up until that point I only used UITableView with dynamic cells. So I tried table views with static sells. It turned out you can only use them inside UITableViewController, and not inside UIViewController with a table view. That got me confused. I couldn’t figure out what was the use of a UITableViewController, since there was no way to customise it. For instance, you can’t add a button at the bottom of the table view if that table view is inside UITableViewController.

Having no luck with static cells I tried using table views with dynamic cells to create settings screens.I used this approach in a couple of projects. It worked, but it wasn’t much of an improvement over using UIScrollView. With scroll view you have to do a lot of work in the Interface Builder. With table view with dynamic cells you have to do a lot of coding.   

Anyway, a couple of days ago I finally figured out how to use UITableView with static cells to create a settings screen. The solution is so simple, I can’t believe I figured it out only now, after 2 years of doing iOS programming.

This is how you do it. You create a UIViewController and a UITableViewController. Then you put your UITableViewController inside your UIViewController, as a child view controller. That’s it. If you want to put a button outside of the table view, just do it in the UIViewController. This is how it may look in your Storyboard. 

The cool thing is that once you created one cell, you can just copy it. Then in your UITableViewController you can make outlets for all your text fields, labels, buttons and other UI elements you have inside the table view. Also, when the keyboard goes up, the table view adjusts accordingly.

Unfortunately, I couldn’t customise the section headers right in the storyboard, so I had to do it programmatically. Here are the only three UITableViewDataSource methods that I implemented:

 

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *