Swift TableView Data Model Class iOS Example Tutorial

swift tableview data model, custom uitableview cell swift

Swift TableView Data Model Class iOS Example Tutorial is Today’s topic.

In this tutorial, you will learn to make tableview with data model class in swift iOS.

Data model class creates MVC structure for iOS app to reduce complexity.

MVC structure helps developer to maintain proper data flow across the tableview to avoid silly mistakes.

We need to create specific swift class which will holds the data items like country name, city name etc. information.

YouTube Output OF Data Model

Move 1. Making Storyboard Works

First of all, make a new project in xCode, as a single view app.

In this step, we will do some important work on Main.storyboard file.

So click on Main.storyboard file. Now see the below image

Swift TableView Data Model
Drag TableView
  • There are two steps in the above image.
  • First of all, using search field, search the “table view”
  • In the second step, drag this Table View to Main Layout. (From Arrow to it’s tail)

Now consider the following image

Swift TableView Data Model
Constraint Pop up
  • Now, make your TableView’s height and width similar with full screen.
  • After this, your table view should look like the above image.
  • Then click the constraint icon as per the step 1 of the above image.

When you click the constraint icon, a pop window will be open as per the below image.

Swift TableView Data Model

  • We have already done the first step of the above image.
  • Now in the pop up window, there are four constraints. Top, bottom, left and right.
  • In the image, I have clicked the top and bottom constraints.

You need to click right and left constraints also. Then click the button (Add 4 constraints) as per the step 4 of the image.

Move 2. DataSource and delegate

Consider the below image,

  • Swift TableView Data Model
    Now it is time to enable DataSource and Delegate for our tableview.
  • First, hold the control key and drag the mouse cursor from tableview to yellow icon at the top of the tableview.(Reference step 1 in above image)
  • Small black screen will be opened, with two options, dataSource and delegate. You need to select both of them.
  • It may happen that for one drag, when you click on dataSource or delegate, black screen is closed. In this situation again repeat the process and select second option this time.

Now attend the below picture,

Swift TableView Data Model
Assistant editor
  • As per the step 1 of above image, click on the assistant editor icon (icon with two circles).
  • When you clicks the assistant editor icon, you will also see the ViewController.swift class on the screen as per the below image.
Swift TableView Data Model
Make Outlet of tableview
  • In the above image, storyboard and ViewController.swift are side by side.
  • As per the step 1, hold the Control key and drag the cursor from storyboard to ViewController.swift
  • As per the step 2, enter the name of the tableview (I have enter “tableview”).
  • After entering the name, click the connect button. We have make an outlet of our tableview.

Now you can see that the below line is auto written, in the ViewController.swift

 @IBOutlet weak var tableview: UITableView!

Move 3. Creating Prototype Cell

Watch the below image


  • As per the step 1 of above image, click on Table View located at the left side bar.
  • Then, as per the step 2, set the number of prototype cells as 1.
  • After this, you can see that one prototype cell is added at the top of the tableview layout.

Now see the following picture


Time to add label into prototype.

  • See the above image, search the label and drag it to the layout of prototype.
  • Create two labels with this method.
  • You can change the text color, size etc of the label with the right hand side bar.
  • After two labels, add a view at the bottom of the prototype cell. Make the background of the view as red. (below image)

Consider the following picture


  • Click on the Table View Cell at the left side bar. (As per first step)
  • Then at the right side bar, enter the identifier of the cell. I have entered “cell” as an identifier.

Move 4. New File

See the following image


  • Now it is time to create a new swift class.
  • as per the above image, click on file->New->file
  • When a new screen appears, select the Cocoa Touch class and hit NEXT button.

Refer the below picture


  • When you reach at the above screen, make sure that Subclass of : column has the value UITableViewCell
  • Name of this file should be “TableViewCell” (value of the class: field)
  • Then click on NEXT and then on CREATE.

Then see the following picture


Time to make connection between cell and a class.

  • Click on cell as per first step of above image. Then click at the blue icon as per the above image.(Blue icon is located at the top of the right side bar, right hand side of the ? icon.)
  • After this, in the class field, write the name of the class we just created. In my case it is : TableViewCell (Step number 2 of image)

Then consider the below picture


Now we will connect the label of the prototype cell with TableViewCell class.

  • For this, open the assistant editor. Open TableViewCell class here.
  • As per the above image, hold the control key and drag the mouse cursor from label to TableViewCell class.
  • Do it with both the labels. Do not do it with view (red background) because we do not want to change the value of the view.

After this step, you can see the below two lines in the TableViewCell.swift class which are auto written.

 @IBOutlet weak var cityName: UILabel!
 @IBOutlet weak var countryName: UILabel!

Move 5. Code for TableViewCell

Final coding lines for TableViewCell.swift file is as the below

//
//  TableViewCell.swift
//  TableViewModel
//
//  Created by Hardik Parsania on 11/20/18.
//  Copyright © 2018 Hardik Parsania. All rights reserved.
//

import UIKit

class TableViewCell: UITableViewCell {

    @IBOutlet weak var cityName: UILabel!
    @IBOutlet weak var countryName: UILabel!
    
    
    override func awakeFromNib() {
       
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

Move 6. Data Model class

Make a new Cocoa Touch class and give it a name DataModel.swift

Write down the following source code in DataModel.swift file

//
//  DataModel.swift
//  TableViewModel
//
//  Created by Hardik Parsania on 11/20/18.
//  Copyright © 2018 Hardik Parsania. All rights reserved.
//

import UIKit

class DataModel {
    
    var country: String?
    var city: String?
    
    init(country: String?, city: String?) {
        self.country = country
        self.city = city
        
    }
}

This class is the model, which creates MVC structure in iOS app.

Move 7. ViewController.swift file’s lines

Final words for ViewController.swift file is as the below

//
//  ViewController.swift
//  TableViewModel
//
//  Created by Hardik Parsania on 11/20/18.
//  Copyright © 2018 Hardik Parsania. All rights reserved.
//

import UIKit

class ViewController: UIViewController , UITableViewDataSource, UITableViewDelegate{

    @IBOutlet weak var tableview: UITableView!
    
    var countryNames: [String] = ["India" ,"US", "Australia", "England", "Germany"]
    var cityNames: [String] = ["New Delhi" ,"Washington", "Melbourne", "London", "Berlin"]
    
    //a list to store DataModel
    var dataModels = [DataModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        //traversing through all elements of the array
        for i in 0..<5{
            
            self.dataModels.append(DataModel(country: String(i) + countryNames[i], city: String(i) + cityNames[i]))
            //displaying data in tableview
            self.tableview.reloadData()
            
        }
        
    }
    
    //the method returning size of the list
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return dataModels.count
    }
    
    //the method returning each cell of the list
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
        
        //getting the hero for the specified position
        let model: DataModel
        
        model = dataModels [indexPath.row]
        
        //displaying values
        cell.countryName.text = model.country
        cell.cityName.text = model.city
        
        return cell
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}

Following two lines are data sources

var countryNames: [String] = ["India" ,"US", "Australia", "England", "Germany"]
var cityNames: [String] = ["New Delhi" ,"Washington", "Melbourne", "London", "Berlin"]
//a list to store DataModel
var dataModels = [DataModel]()
  • These are string arrays and we will use then to set up the object of DataModel class.
  • Third line is making array with objects of DataModel class (dataModels).
  • for loop in the viewDidLoad() method, will populate the data from string arrays to dataModels.

See the below method

//the method returning each cell of the list
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
        
        //getting the hero for the specified position
        let model: DataModel
        
        model = dataModels [indexPath.row]
        
        //displaying values
        cell.countryName.text = model.country
        cell.cityName.text = model.city
        
        return cell
        
    }

Above method or function will create the each row cell of the table view.

Download Source Code For Swift TableView Data Model

Download TableViewModel Example