Skip to main content

Getting Started with UITableViewController in Swift (How to use Table View Controller in IOS)

The table view controller is an instance of UITableViewController class. You can use this class in order to display structured repeatable information in vertical list in IOS applications. 

In this tutorial I will show you step by step how the table view controller works and how you can use it in your applications. 

Component in table view controller 

Working with table view controller, include few IOS development concept such as delegation design pattern, subclassing, and reusing the views. So, let’s understand the base component in order to build and run table view controller in your app.

Table view

The table view is the view, which displays on the screen and the table cell will be listed on table view. The table view is an instance of UITableView class.

Table view cell

The table view cell is an instance of UITableViewCell, It is repeatable rows shown in it. You can use this subclass to create a custom table view cell .

Table view Delegate

The table view delegate is an instance of UITableViewDelegate class. This delegate class is responding to the user interaction event and responsible for managing the layout of  the table view.

Table view Data source 

The table view data source is an instance of UITableViewDataSource class. It is responsible for managing the data in a table view including the table view section and cells.

How the table view controller works

We described you the component of table view controller and now we need to understand that how the table view controller works on your application. Hope you are familiar with the Model view controller architecture pattern in IOS development. The table view controller uses this pattern perfectly like table view and table view cells are view and controller is a controller.
The table view and table view cells are always responsible for displaying the information to the user interface. Controllers are responsible for managing the data, implementing the logic and taking the decisions. 

Setting Up Table View Controller 

We understood that theoretically how table view controller work, now its the time to put them into practical based to build the simple table view controller application. Here let me explain what are the functions needed to make things happened. 

In Xcode you can use different approaches in building user interface component, but here I am going to use default table view controller with interface builder using storyboard.

Creating a Demo Project 

Creating a demo project for this application as shown in the following screen 


Lets open a single view application. 
Named it as “DemoTableviewController”.
Delete “ViewController” class and ViewController view in storyboard.

The process of creating a table view controller 

Add “TableViewController” to storyboard.
Adding Table view controller class. Right click on your project name and select “New File”.
Select subclass of “UITableViewController” and name it as “RecipeTableViewController” as shown in below picture.
To configure table view controller with table view controller class. Select table view controller in storyboard and select “RecipeTableviewController” in Identify Inspector.

Now build and run your application, it will open up with a black screen, so to fix this again select view RecipeTableviewController’s view in storyboard and check “is initial View Controller” in Attributes inspector. Again build and run, it will open up with following screen.



Now if you see your project navigator section a new file has been added called “RecipeTableViewController.swift”. You need to implement required function in this file in order to build  table view controller on this app.

If you look at the file closely “RecipeTableViewController.swift” you can view some default methods have been added by default, which will be used to make things happened. Those methods are as follows:

override func numberOfSections(in tableView: UITableView) -> Int 

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 

Setting up table view controller data source 

Now you will need to implement different function to make this table view controller work. These function either belongs to UITableviewControllerDelegate or UITableviewControllerDatasource. Let me show you what are the functions we needed and how we can divide into these categories. 

The table view controller datasource methods:

func numberOfSections(in tableView: UITableView) -> Int

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

The table view controller delegate methods

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 

Setting up Recipe Array 

Let’s setup recipe array as follows, which recipe name will be displayed on the table view cell. Please copy and paste this code in “RecipeTableViewController.swift“ under header section.

let recipeList = ["Fish Curry", "Chicken Burger", "KFC Chicken", "Roasted Garlic Speghathi", "Spaghetti Grilled Cheese", "Pizza", "Chicekn Shawarma", "BBQ Spaghetti", "Mushroom Soup", "BBQ Chicken", "Chicken Soup", "Kebab Chicken", "Lamb Chops", "Lamb Shank", "Lamb Cutlets", "Prawn Curry", "Prawn Biryani", "Dynamite Prawns”]

Implementing Number of Sections 

This is first datasource method that we are going to implement. It asks how many sections you need in your table view controller. Of course we are going to display only recipe list in this application. So, it should be one section. Let’s write the code as follows.

override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

Implementing number of rows in section 

We need to implement second datasource method that how many cell we need to display on that section, which mean each cell correspond to a row in the table view. it should be number of items in the recipe array equals to number of rows in section. So, the code should be similar to this 

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.recipeList.count
}

Implementing cell to table view controller 

This is the most important section in table view controller, which provides the cells to the table view controller. This section combine with some important components, which need to be familiar when implementing a table view controller in the app.

What is index path 
What is reusable identifier. 

Basically in this tutorial we have only one section, which need to display the recipes. So, index path contain the information about each rows on this section. When this function is called we need to get recipe cell based on index path as follows.

let recipe = self.recipeList[indexPath.row]

The main purpose of “dequeueReusableCellWithIdentifier” is to use less memory as we know that our handheld devices comes with the limited memory. Basically “dequeueReusableCellWithIdentifier” initialize the particular number of cells that we created for the visible part of the tableview and the cells will use it again for further processing. The code is as shown below:

let cell = tableView.dequeueReusableCell(withIdentifier: "recipeCell", for: indexPath)

Here “recipeCell" before we use, which need to be configure in storyboard as shown in below screen.



So, now lets implement this function to display the recipe name on table view controller as shown in below method:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "recipeCell", for: indexPath)
        cell.textLabel?.text = self.recipeList[indexPath.row]
        return cell
    }

Finally, build and run your application it will show the recipe list as shown below screen



Implementing Single cell Selection 

This is one of the table view controller delegate methods. When someone click on particular cell whether you need to display any notification or move to different view controller to display details view. Its up-to you how you are going to develop your application. Here I just show you when you select on particular recipe, It will print the recipe name on Xcode console as follows: 

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let singleRecipe = self.recipeList[indexPath.row]
        print(singleRecipe)
    }

What is Next?

You can work with table views without using a table view controller. Simply add a UITableView object  to a view controller and implement it with table view delegate and data source methods.

The UITableViewController class provides default implementations of table view delegate and table view data source methods. This is a critical feature of working with table view controller. 

As you’ll see in the next chapters of this article, we’ll override these functions with our own implementations. We can customize the table view controller by doing it.

Source Code

The source code for this DemoTableViewController app is on Github repository. You can clone the repo and run the completed app.

$ git clone https://github.com/rizvisaf/DemoTableViewController.git
$ cd DemoTableViewController
$ open DemoTableViewController

Comments