In our demo application, we have provided an implementation for some methods to display data in the table view, mentioned the number of sections and rows, and specify headers and footer information for each section.
The data source defines methods to handle the data, and the delegate protocol defines methods to handle custom behavior and interactivity, and custom appearance.
So let's go to the TableViewDemo project again open Main.storyboard. Right-click on the Table View and connect the circle beside the delegate to the View Controller.
Now let's go the ViewController.swift file and add a comma followed by UITableViewDelegate.
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
}
In Swift, you can only inherit from a single class, we are inheriting from the UIViewController class, but there's no limit to the number of protocols you can choose to support. There are multiple optional methods available like;
So let's add one of the simpler options is what will happen when a row is selected, and that method is defined in the UITableViewDelegate protocol.
If you provide that method, it will automatically be called, so let's add the implementation for this method ViewController class.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You select row \(indexPath.row) in section \(indexPath.section) ")
}
This method will automatically be called whenever somebody touches a row, and it will also give the section number and the row number. We have added a simple print statement to show that selected row and selected section. Let's run the application.
If you touch one of these rows to select you should see a message in the console view of Xcode. So we could use this method to prepare to move to another screen and use that selected row to make sure we've passed over any information that we need on that next screen.