Organize TableView efficiently in iOS

Tram Ho


TableView is one of the components commonly used in iOS applications. In this article, we will analyze and step by step organize the Table View effectively to easily maintain and apply a variety of data requirements.

Suppose we need to build a TableView with many different types of cells, as shown below:

With the following requirements:

  • The displayed data will be retrieved through the API call
  • Sections without data are not displayed

We will choose the MVVM model for the example of this article. With MVVM, it will be easy to separate the View and the profession of the problem. In this example we will create a TableView with 3 different types of cells:

  1. Cell only has labels
  2. Cell contains pictures and labels
  3. Cell has an extension function

Step 1: Create a new ViewController and Storyboard

We will first create a Storyboard for the dynamic TableView, and add a TableView into the UIViewController.

Then the code of ViewController will look like this:

Step 2: Create protocol for TableViewCell and TableViewCellModel

We will create 2 protocols for:

  1. For the TableView cell
  2. For TableView cell ViewModel

We will create the TableViewCellViewModelProtocol protocol for the ViewCell model. The variable cellIdentifier will be used to distinguish between cell types.

Next we create the TableViewCellProtocol protocol for ViewCell. This protocol has a populate method that is used to get the data inside TableViewCell

Step 3: Create TableViewCell and TableViewCellViewModel

We will proceed to create 3 TableView cells and display data based on ViewModel.

Type 1: TableView cell has only label

The ViewModel will have the following property:

  • cellIdentifier
  • title

The ViewCell would look like this:

Type 2: TableViewCell includes image and label

In the cell will include 1 image and 1 label as shown below.

The cell model would look like this:

Cell View will look like this:

Type 3: Cell with extension functions

The cell model would look like this:

Cell View will look like this:

Step 4: Create ViewModel for UIViewController

ViewModel for UIViewController will include 2 main functions:

  • Update data for TableView
  • Update data for one line

We will use an array of TableViewCellModelProtocol object to store the content and processing of each row in the table.

Then the data in the table will be initialized as follows:

Step 5: Combine the TableView delegate and the DataSource

In this step we will progress the Delegate and DataSource initialization for the table.

We will then write implementations for the closures in the ViewModel defined in step 4:

Finally, we will implement the methods of UITableViewDelegate and DataSource to return the content of the desired cells.

Then our table will behave as shown below

Reference source

Share the news now

Source : Viblo