Two UITableViews One UIViewController
That must be chocolate ice-creme
Difficulty: Beginner | Easy | Normal | Challenging
UITableView: A view that presents data using rows arranged in a single column
View controller: Sits between the view and the model, tying them together (usually using the delegate pattern). The controller is not tightly bound to a concrete view, and communicates via a protocol to an abstraction. An example of this is the way that a UITableView communicates with its data source through the UITableViewDataSource protocol. Think of it as the how of the App. The primary job of the controller is to format the data from the model for the view to display.
What would happen if I were to whack two
UITableView instances into a single view controller?
How might both instances communicate with the dataSource and the delegate?
Certainly the solution would look like the following:
Let us see how we can put this into action!
Setting up the storyboard
You could also attempt this programatically (or however you want to, I don’t even know you so go wild).
In my case, I added a stack view to keep everything tidy, and spaced two tableview instances equally with a spacing of 8 between them. You can see the completed view amongst the completed project @The repo link.
The outlets and data
Within the brilliantly named
UIViewController ViewController we set up a couple of outlets for the
UITableView instances, and prepare some (creative) data for them to display.
The viewDidLoad function
This is then followed up in the
viewDidLoad() function by setting up the cell for reuse.
We can see that the delegate and the data source for each
UITableView instance has been set to the same viewController. Don’t worry — this will be dealt with in the following code.
The minimal implementation of
tableView(_:cellForRowAt:). The question is which tableView is the function called from? It turns out that this is called by both, however one of the function parameters is actually the tableview.
Now the example uses a simple if statement (although any switch or branching method would be suitable here) to behave with the appropriate
Therefore the correct cell is returned depending on the
UITableView appropriate to the function call.
A similar exercise can take place using the
Creating a table view is really important when creating Apps using the iOS SDK.
Putting two such objects on the same Storyboard might seem like something that you don’t do frequently, however it is also something that you should know how to do as you might be able to think of some interesting uses for this skill.
Have fun coding!
I’d love to hear from you if you have questions