In Xcode, there is a project template option called the Master-Detail App, which already includes a configured table view, but it has a lot of other functionality as well. Here we will focus only on Table View, so let's create a new blank Single View App and call it TableViewDemo
Once the project is created, go into Main.storyboard, and from the Object library find and drag a Table View.
Now resize it to take up the full contents of the available space.
Right click on the table and you will see a popup.
Click the circle beside dataSource and drag it over to the ViewController in Document Outline.
You should now see a filled circle, dataSource is now connected to ViewController.
The Table View will now expect to find its necessary methods in our ViewController class file, so let's go and write them.
Open the ViewController.swift file, and in the class declaration, you can see that the class ViewController inherits from UIViewController class. After that add ", UITableViewDataSource" as shown below.
This is not a class name; it is a protocol name, a protocol being a formal list of methods and properties that we can volunteer to provide.
Now many of these methods are optional, in fact, only two of them are marked as required. The two methods marked as required are the tableView numberOfRowsInSection, and tableView cellForRowAt IndexPath.
So let's add the required methods by clicking the red circle in pop-up error and click Fix button.
Xcode now provides the stubs for our two required methods, numberOfRowsInSection, and cellForRowAt indexPath.
NumberOfRowsInSection will be called, and we just need to return an integer value of how many many rows we want in a section, so let's return 20.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
In the next method, we need is cellForRowAt indexPath, providing the content of the cell for each row in the table view.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = "This is the cell for \(indexPath.row)"
return cell
}
Let's run your application.