Since I read the objc.io post about light view
controller,
every few month I come back to the same problem: find the best way to
write a table view controller. I have tried several different approaches
like putting the data source and delegate in a separate class or using
MVVM to populate the cell.
This post is the March 2016 solution to this problem. And as most of the
times, I’m quite happy with the current solution. It uses generics,
protocols and value types.
The main part is the base table view controller. It holds the array to
store the model data, is responsible for registering the cell class and
it implements the needed table view data source methods.
Let’s start with the class declaration:
The base table view controller is a generic subclass of UITableViewController.
The placeholder type name Cell is of type UITableViewCell and
conforms to the protocol Configurable. The
protocol is very simple. It just defines one method:
The cell will be registered and dequeued in the TableViewController.
This means it is enough to have a private property for the cell
identifier:
Next we need an array to hold the data to be presented in the table
view:
Whenever the data is set, reloadData() of the
table view is called and the table view is scrolled to top. Next, we
define an init method:
In viewDidLoad() we set up the table view:
What’s left is to provide the required method if UITableViewDataSource:
The only interesting part of these methods is the line
cell.config(withItem: data[indexPath.row]). This means the cell is responsible to
fill it’s labels or what ever the cell uses to present the data.
Here is the complete base table view controller class:
We can use this base class to define a table view controller that let’s
the user put in a string and search on Github for matching users:
That is a complete table view controller. Most of the code is for the
presentation and handling of the searchBar. Neat, isn’t it?
With all this, an instance of UserSearchTableViewController
can be initialized like this:
For completeness, here is a possible version of TwoLabelCell:
You can find the code and another table view controller using the same
structure on Github.
Update April 1st 2016: Improved the code after a discussion about it in
the Swiftde-Slack group.