Adding the data source and delegate

As discussed in the previous chapter, we need to add a data source and delegate to our Table View. Table View uses dynamic cells, which we are required to add:

  1. Select Table View in the Outline view, and then Connections inspector in the Utilities panel.
  2. Click on and drag from dataSource to the Location View Controller in the Outline view:
  1. Repeat with the delegate property:
  1. In the Utilities panel, select the Attributes inspector, if not already selected, and make sure you have the following values:

Next, for us to display anything in Tableview, we need to add the UITableViewDataSource protocol. Our protocol requires that we implement the following three methods. Add the following after the closing curly brace of viewDidLoad():

Let's break down the code to understand what we are doing:

tableView(_:numberOfRowsInSection:)
return 15
numberOfSections(in:)
return 1
tableView(_:cellForRowAt:)
let cell = tableView.dequeueReusableCell(withIdentifier: "locationCell", for: indexPath) as UITableViewCell
cell.textLabel?.text = "A cell"

Since we do not have any data yet, we set our label to A cell. The textLabel variable is the default label we got when we selected a basic cell.

return cell

Let's build and run the project by hitting the Play button (or using cmd + R) to see what happens. You should now see A cell repeating 15 times: