TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

iOS | TableView

iOS | TableView with XCode IDE Introduction, History and Versions, Views and View Controllers, Creating the first iOS application, Label, Button, TextField, Switch, Segmented Control, iOS UI Controls, iOS UI Views, iOS UIView Controllers, Tab Bar Interface etc.

<< Back to IOS

TableView

TableView can be defined as the view which can arrange the data using rows in a single column. It is used in almost every iOS application, for example, contacts, facebook, Instagram, etc. The tableview is the instance of the UITableView class, which inherits the UIScrollView class. We will discuss UIScrollView in the upcoming chapters of this tutorial.

class UITableView : UIScrollView

In iOS applications, whenever we need to display the single column containing vertically scrolling content, we use tableview. The tableview can display multiple records (divided into rows), which can be scrolled vertically if needed. Each row of the tableview presents each record of the data source. For example, in the contact app, we display each contact name in the separate row of the tableview, and we get the details related to the contact on the click to that row.

The below image shows how the tableview is used to display data in the settings app.

iOS TableView

The below image shows how the tableview is used in the Contact app.

iOS TableView

We can create the sections in the tableview to group the related rows, or we can show the long list of records in multiple rows without sections.

In iOS applications, the tableview is used in the association with the navigation controller to organize the data hierarchically. Here, we can navigate between different levels of hierarchy using the navigation controller.

The appearance of the tableview is managed by UITableView class, which inherits UIScrollView. In tableview, the row is simulated by the object of the UITableViewCell class, which can be used to display the actual content. We can customize the tableview cells to display any content in the iOS application.

Adding UITableView to interface

To add the tableview to the storyboard, search for the Tableview in the object library and drag the result to the storyboard.

iOS TableView

To use the tableview, we need to set its delegate and data source properties. The tableview is a data-driven object, i.e., it gets the data to be shown from the data source object. In the real-world applications, the data source object contains the data which is returned by an API call from the database server.

The delegate and data source properties of the tableview can be set by using the following line of code in the viewDidLoad method of ViewController.

tableView.delegate = self
tableView.datasource = self

TableView Delegate Methods

The tableview delegate methods are defined to add the following features to the tableview.

  • We can create the custom headers and footers for the sections in the tableview.
  • We can specify the custom heights for rows, headers, and footers.
  • Provide height estimates for the rows, headers, and footers.
  • We can define the method which can handle the row selections.
SN Method Description
1 func tableView(UITableView, willDisplay: UITableViewCell, forRowAt: IndexPath) The tableview notifies this delegate when it is about to draw a cell for a particular row.
3 func tableView(UITableView, willSelectRowAt: IndexPath) -> IndexPath? The tableview notifies this delegate method when the specified row is about to be selected.
4 func tableView(UITableView, didSelectRowAt: IndexPath) This delegate is notified when the specified row of the tableview is selected.
5 func tableView(UITableView, willDeselectRowAt: IndexPath) -> IndexPath? This delegate is notified when the particular cell is about to be deselected.
6 func tableView(UITableView, didDeselectRowAt: IndexPath) This delegate is notified when the particular row is deselected.
7 func tableView(UITableView, viewForHeaderInSection: Int) -> UIView? This delegate method returns a UIView which represents the header of the tableview.
8 func tableView(UITableView, viewForFooterInSection: Int) -> UIView? This delegate method returns the uiview, which represents the footer of the tableview.
9 func tableView(UITableView, willDisplayHeaderView: UIView, forSection: Int) This delegate method is notified when the tableview is going to display the headerview for the particular section.
10 func tableView(UITableView, willDisplayFooterView: UIView, forSection: Int) This delegate method is notified when the tableview is going to display the footer view for the particular section.
11 func tableView(UITableView, heightForRowAt: IndexPath) -> CGFloat This delegate method returns the height for the row.
12 func tableView(UITableView, heightForHeaderInSection: Int) -> CGFloat This delegate method returns the height of the header of section in the tableview.
13 func tableView(UITableView, heightForFooterInSection: Int) -> CGFloat This delegate method returns the height for the footer of a particular section in the tableview.
14 func tableView(UITableView, estimatedHeightForRowAt: IndexPath) -> CGFloat It asks the delegate for the estimated height of the row in a particular location.
15 func tableView(UITableView, estimatedHeightForHeaderInSection: Int) -> CGFloat It asks the delegate for the estimated height of the header in a particular location.
16 func tableView(UITableView, estimatedHeightForFooterInSection: Int) -> CGFloat It asks the delegate for the estimated height for the footer in the particular section.

TableView DataSource Methods

To maintain the data to be displayed by the tableview, we need to maintain a DataSource object that implements the UITableViewDataSource protocol. The datasource object manages the tableview data. The datasource object performs the following main tasks.

  1. It reports the number of rows and sections to be displayed in the tableview.
  2. It allocates the reusable cells for each row in the tableview.
  3. It provides the titles for headers and footers in the tableview sections.

To perform the above-mentioned tasks, there are some functions defined in the UITableviewDataSource protocol. The following table contains the important methods defined in the protocol.

SN Method Description
1 func tableView(UITableView, numberOfRowsInSection: Int) -> Int This method returns the number of rows to be displayed in the section of the tableview.
2 func numberOfSections(in: UITableView) -> Int This method returns the number of sections to be displayed in the tableview.
3 func tableView(UITableView, cellForRowAt: IndexPath) -> UITableViewCell This method returns the object of a UITableViewCell, which shows the actual content of a particular row in the tableview. This method inserts the cell for a particular row in the tableview.
4 func tableView(UITableView, titleForHeaderInSection: Int) -> String? This method returns a string representing the title of the header in the section of the tableview.
5 func tableView(UITableView, titleForFooterInSection: Int) -> String? This method returns a string representing the title of the footer in the section of the tableview.
7 func tableView(UITableView, canEditRowAt: IndexPath) -> Bool It asks the DataSource to verify whether the particular row is editable or not.
8 func tableView(UITableView, canMoveRowAt: IndexPath) -> Bool It asks the DataSource to verify whether the particular row can be moved to another location in the tableview.
9 func tableView(UITableView, moveRowAt: IndexPath, to: IndexPath) This method moves the specific row to some other location in the tableview.
10 func sectionIndexTitles(for: UITableView) -> [String]? It returns the array of the string containing the titles for the sections in the tableview.

There are two methods that are required to be defined if the ViewController implements the UITableViewDatasource protocol, which is mentioned in the following code.

extension ViewController : UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSourceArr.count
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "cell text"
               
        return cell
    }
    
}

Example 1

In this example, we will create a simple tableview which displays a list of top 10 programming languages in 2019. In this example, we will use UITableView to create the interface builder and the delegate and datasource methods to set the data in the tableview.

Interface Builder

In this example, we will create the following view controller by adding the tableview to the interface builder. We will also use the label object to show the title of the tableview. We will add a prototype cell to this tableview and assign ViewController.swift class for this ViewController.

iOS TableView

ViewController.swift

In ViewController.swift, we will create the connection outlet of the tableview added to the storyboard. We will also define the delegate and datasource methods to display the tableview data.

import UIKit
class ViewController: UIViewController {


    @IBOutlet weak var tableView: UITableView!
    var dataSourceArr = Array<String>()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        tableView.delegate = self
        tableView.dataSource = self
        dataSourceArr = ["Python","JavaScript","Java","Swift","GoLang","C#","C++","Scala"]
        
        
    }


}


extension ViewController : UITableViewDelegate{
    
}


extension ViewController : UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSourceArr.count
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = dataSourceArr[indexPath.row]
        cell.textLabel?.textAlignment = .center
        return cell
    }
}

Output

iOS TableView

Example: Handling multiple sections in the tableview

In this example, we will create the multiple sections in the tableview, and we will define the variable number of rows and row content depending upon the particular section.

Interface Builder

To create the interface builder for this example, we need to add a tableview and add a prototype cell for the tableview. The interface builder looks like the below image with a prototype cell.

iOS TableView

ViewController.swift

import UIKit


class ViewController: UIViewController {


    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        tableView.delegate = self
        tableView.dataSource = self
    }
    
}


extension ViewController: UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            return 2
        }
        else if section == 1{
            return 3
        }
        else if section == 2{
            return 4
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        if(indexPath.section == 0){
            cell.textLabel?.text = "Row in section 1"
        }
        else if(indexPath.section == 1){
            cell.textLabel?.text = "Row in section 2"
        }
        else if(indexPath.section == 2){
            cell.textLabel?.text = "Row in section 3"
        }
        return cell
    }
}


extension ViewController : UITableViewDelegate{
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Section " + (section+1).description
    }
    
}

Example 2: Customizing Table View cell

In this example, we will customize the tableview cell by assigning it to a class and creating the outlets of the cell objects in that class. In most of the iOS applications, there are the requirements to customize the tableview class since we can-not always fulfill our requirements by just setting the label text of the cell.

This example simulates the list view of the products shown in the ECommerce Application.

Interface Builder

To create the interface builder for this example, we need to add the tableview to the view controller and add the prototype cell into it. In the content view prototype cell, we will add a uiview to which, we will add an UIImageView and UILabel objects. The following image shows the storyboard in the example.

iOS TableView

MyTableViewCell.swift

MyTableViewCell inherits the UITableViewCell class, which is assigned to the prototype cell of the tableview. In this class, we can instantiate the image view and label objects.

import UIKit


class MyTableViewCell: UITableViewCell {


    @IBOutlet weak var titleImg: UIImageView!
    
    @IBOutlet weak var titleLbl: 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
    }


}

ViewController.swift

import UIKit

class ViewController: UIViewController {
    
    var imgArr = ["Product1","Product2","Product3","Product4","Product5","Product6","Product7","Product8"]
    var lblTextArr = ["Powerbanks","Storage Devices","LED Bulbs","Laptop Bags","Keyboards","Routers","Shoes"]
    
    @IBOutlet weak var tableView: UITableView!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        tableView.delegate = self
        tableView.dataSource = self
    }
    
}




extension ViewController : UITableViewDataSource{
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return imgArr.count - 1
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
        cell.titleImg?.image = UIImage(named: imgArr[indexPath.row])
        cell.titleLbl.text = lblTextArr[indexPath.row]
        return cell
    }
}


extension UIViewController : UITableViewDelegate{
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 150
    }
    
}
iOS TableView




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf