How to use UITableView in Swift

October 7, 2017

In this tutorial we will see how to use the UITableView in iOS

First you create single view application using XCODE
Then you place the UITableView control from the Object Library in to ViewController in your story board

To work with UITableView you need two protocols UITableViewDelegate and UITableViewDataSource

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
  var days: [String] = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
  @IBOutlet weak var tableView: UITableView!


}

In above code we have days array to hold data to pass to the Tabelview. You can see the IBOutlet for the UITableview

With UITableViewDataSource protocol you have to conform two methods

func tableView(UITableView, cellForRowAt: IndexPath)

Asks the data source for a cell to insert in a particular location of the table view.

func tableView(UITableView, numberOfRowsInSection: Int)

Tells the data source to return the number of rows in a given section of a table view.
Now You can see the full source code for above two methods

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.days.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell")!
        cell.textLabel?.text = self.days[indexPath.row]
        return cell
    }

First methods returns number of rows in the array
Second method return UITableViewCell object with assigning array element to it

Final thing you have to do is register your UITableViewCell and give them an identifier in viewDidLoad() function

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

Now lets look at the full source code of the ViewController.swift

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var days: [String] = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.days.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell")!
        cell.textLabel?.text = self.days[indexPath.row]
        return cell
    }
    

}

You can have following output when you run the application

Touch your table row
If you want to popup alert when you touch the table row you can use the following code

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
        let alert = UIAlertController(title: "Hello", message: days[indexPath.row], preferredStyle: UIAlertControllerStyle.alert)
        // add OK button
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }

Note

I have experienced occasionally that UITableView not visible with data which we put in array. In those situations you can use following code inside the viewDidLoad() method

 
tableView.delegate = self
tableView.dataSource = self