Skip to content

Table views basics (Swift)

Prepared and tested with Xcode 9.2 and Swift 4 (steps 1-9, 2018-03-03) and Xcode 10.2 (step 10 and step 11, 2019-04-08)

In this tutorial we cover the following topics


General information

Technically, a table view is the view object that displays a table’s data which is an instance of the class UITableView. Each visible row in a table is implemented by an instance of the UITableViewCell class. Table views are not responsible for storing table’s data. They store only enough data to draw the rows that are currently visible. Table views get their configuration data from an object that conforms to the UITableViewDelegate protocol and their row data from an object that conforms to the UITableViewDataSource protocol.

We can also put more data, than standatd title and details one-line strings, in a cell if we need to by adding subviews to UITableViewCell. We do this using either by adding subviews programmatically when creating the cell or by loading them from a storyboard or nib file.

Table views come in two basic styles

  • Grouped A grouped table view contains one or more sections of rows. Within each section, all rows sit tightly together in a nice little group; but between sections, there are clearly visible gaps.
  • Plain This is the default style. In this style, the sections are slightly closer together, and each section’s header can optionally be styled in a custom manner. When an index is used, this style is also referred to as indexed.


Introduction

  1. Step 1: create a new project
    Create a new project

    1. Select File | New | Project...
    2. Select Single View Application on the template selection sheet.
    3. As the product name enter Swift iOS Table View Basic
    4. Set the Language to Swift. Because we will not use tests in this tutorial, you can leave both test check boxes unchecked as well as make sure the check box labeled Use Core Data is also unchecked.
  2. Step 2: add Table view and set connections
    1. Select Main.storyboard to edit the storyboard.
    2. Find in the object library a Table View and drag it over to the View window.
    3. Add all necessary constraints to make sure that the table view is positioned and sized correctly.
    4. Select the table view in the Document Inspector and bring up the Connections Inspector (use shortcut: Alt + Command + 6)
    5. Drag from the circle next to dataSource and delegate in Outlets section to the View Controller icon in the Document Outline

      or above the view controller in the storyboard editor.

      This makes our controller class both the data source and delegate for this table.
  3. Step 3: add a code
    1. Single-click ViewController.swift and add the following code
      //
      //  ViewController.swift
      //  Swift iOS Table View Basic
      //
      //  Created by Piotr Fulmański on 2018.03.07.
      //  Copyright © 2018 Piotr Fulmański. All rights reserved.
      //
      
      import UIKit
      
      class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
          var eightThousandersPeaks = [String]()
          
          override func viewDidLoad() {
              super.viewDidLoad()
              // Do any additional setup after loading the view, typically from a nib.
              
              eightThousandersPeaks += ["Mount Everest", "K2", "Kangchenjunga",
                                       "Lhotse","Makalu", "Cho Oyu",
                                       "Dhaulagiri","Manaslu", "Nanga Parbat",
                                       "Annapurna I", "Gasherbrum I", "Broad Peak",
                                       "Gasherbrum II", "Shishapangma"]
          }
          
          override func didReceiveMemoryWarning() {
              super.didReceiveMemoryWarning()
              // Dispose of any resources that can be recreated.
          }
      
          func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
              return eightThousandersPeaks.count;
          }
          
          func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
              // Trick to get static variable in Swift
              struct staticVariable { static var tableIdentifier = "TableIdentifier" }
              
              var cell:UITableViewCell? = tableView.dequeueReusableCell(
                  withIdentifier: staticVariable.tableIdentifier)
              
              if cell == nil {
                  cell = UITableViewCell(style: .default, reuseIdentifier: staticVariable.tableIdentifier)
              }
              
              cell?.textLabel?.text = eightThousandersPeaks[indexPath.row]
              return cell!
          }
      }
      

  4. Step 4: using table view cell styles
    Except the default UITableViewCellStyleDefault the UITableViewCell class includes several other predefined cell styles that let us easily add a bit more variety to our table views. These cell styles use three different cell elements

    • Text label This is the cell’s main text. In the case of the default style UITableViewCellStyleDefault the text label is the only text shown in the cell.
    • Detail text label This is the cell’s secondary text, usually used as an explanatory note or label.
    • Image If an image is part of the specified style, the image is displayed to the left of the cell’s text.

    Let's see all of them

    1. Single-click ViewController.swift and to enable detail text label add/modify the following code
      			
      //
      //  ViewController.swift
      //  Swift iOS Table View Basic
      //
      //  Created by Piotr Fulmański on 2018.03.07.
      //  Copyright © 2018 Piotr Fulmański. All rights reserved.
      //
      
      import UIKit
      
      class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
          var eightThousandersPeaks = [String]()
          var eightThousandersPeaksHeight = [String]()
          
          override func viewDidLoad() {
              super.viewDidLoad()
              // Do any additional setup after loading the view, typically from a nib.
              
              eightThousandersPeaks += ["Mount Everest", "K2", "Kangchenjunga",
                                       "Lhotse","Makalu", "Cho Oyu",
                                       "Dhaulagiri","Manaslu", "Nanga Parbat",
                                       "Annapurna I", "Gasherbrum I", "Broad Peak",
                                       "Gasherbrum II", "Shishapangma"]
              
              eightThousandersPeaksHeight += ["8850", "8611", "8586",
                                              "8516", "8463", "8201",
                                              "8167", "8156", "8126",
                                              "8091", "8068", "8047",
                                              "8035", "8013"]
          }
          
          override func didReceiveMemoryWarning() {
              super.didReceiveMemoryWarning()
              // Dispose of any resources that can be recreated.
          }
      
          func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
              return eightThousandersPeaks.count;
          }
          
          func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
              // Trick to get static variable in Swift
              struct staticVariable { static var tableIdentifier = "TableIdentifier" }
              
              var cell:UITableViewCell? = tableView.dequeueReusableCell(
                  withIdentifier: staticVariable.tableIdentifier)
              
              if cell == nil {
                  cell = UITableViewCell(style: .subtitle, reuseIdentifier: staticVariable.tableIdentifier)
              }
              
              cell?.textLabel?.text = eightThousandersPeaks[indexPath.row]
              cell?.detailTextLabel?.text = eightThousandersPeaksHeight[indexPath.row]
              return cell!
          }
      }
      

    2. Let's change table view cell styles again. Single-click ViewController.swift and to enable detail text label add/modify the following code
      ...			
              if cell == nil {
                  cell = UITableViewCell(style: .value1, reuseIdentifier: staticVariable.tableIdentifier)
              }
      ....
      

    3. Let's change table view cell styles again. Single-click ViewController.swift and to enable detail text label add/modify the following code
      ...			
              if cell == nil {
                  cell = UITableViewCell(style: .value2, reuseIdentifier: staticVariable.tableIdentifier)
              }
      ....
      

  5. Step 5: add an image
    For all style except UITableViewCellStyleValue2 we can add an icon.

    1. Prepare two images: one for selected row and second for not selected. In my case I have two dots (red and green) 24 pixels height and 24 pixels width. Both should be prepared in 3 sizes to be compatible with retina displays
    2. Click Assets.xcassets in the project navigator to bring up the Asset Catalog for the project and drag and drop images (every image in three different scales)
    3. Single-click ViewController.swift and add/modify the following code
      	
      class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
      	
          ...
          
          func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
              
              ...
              
              cell?.detailTextLabel?.text = eightThousandersPeaksHeight[indexPath.row]
              
              let image = UIImage(named: "dot_green")
              cell?.imageView?.image = image
              let highlightedImage = UIImage(named: "dot_red")
              cell?.imageView?.highlightedImage = highlightedImage
              
              return cell!
          }
      }	
      

      Swift 3 introduces Image Literals (Be Literal!)

  6. Step 6: handling row selection
    Now we are going to implement the delegate method that is called after a row has been selected.

  7. Single-click ViewController.swift and add/modify the following code
    	
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            // Get data from model
            let textLabel = eightThousandersPeaks[indexPath.row]
            let selectedCell = tableView.cellForRow(at: indexPath)
            // Get data from cell
            let detailTextLabel = selectedCell?.detailTextLabel?.text
            let message = "You selected \(textLabel) (\(detailTextLabel ?? "no details"))"
            
            let alert = UIAlertController(title: "Information",
                                               message: message,
                                               preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "Close",
                                             style: .default,
                                             handler: nil)
    
            alert.addAction(cancelAction)
            self.present(alert, animated: true)
            
            tableView.deselectRow(at: indexPath, animated: true)
        }	
    

    More abut alerts can be found at How To: Displaying Alerts With UIAlertController In Swift

  8. Step 7: disable row selection
    The second table’s delegate method that allow us to handle row selection is tableView(_:willSelectRowAt:) which is called before the row is selected. It can be used to prevent the row from being selected or even to change which row gets selected.

  9. Single-click ViewController.swift and add/modify the following code
    	
        func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
            let detailTextLabel = self.eightThousandersPeaksHeight[indexPath.row]
            
            if let height = Int(detailTextLabel) {
                if (height < 8500) {
                    print("\(height) is lower than 8500m limit")
                    return nil;
                } else {
                    return indexPath;
                }
            } else {
                return nil
            }
        }
    

  10. Step 8: delete TableView row when swipe
    Note: This is very basic method available from iOS 2.0 (How to swipe to delete UITableViewCells). Another (and preferred) method to complete this task is described in step 10.

    1. Single-click ViewController.swift and add/modify the following code
          func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
              return true
          }
          
          func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle,
                         forRowAt indexPath: IndexPath)
          {
              if editingStyle == .delete
              {
                  eightThousandersPeaks.remove(at: indexPath.row)
                  eightThousandersPeaksHeight.remove(at: indexPath.row)
                  tableView.reloadData()
              }
          }
      

  11. Step 9: making table cells reorderable
    1. To enable editing mode for a table view, create an outlet: hold down the Control key and drag the mouse from the Table View to the ViewController.swift class code

      This should add the following code

      			
      class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
          ...
          
          @IBOutlet weak var tableView: UITableView!
          
          override func viewDidLoad() {
      	...
      	}
      	...
      }		
      
    2. Having an outlet add/modify the following code
      			
          override func viewDidLoad() {
              super.viewDidLoad()
              // Do any additional setup after loading the view, typically from a nib.
              self.tableView.isEditing = true
              eightThousandersPeaks += ...
              ...
          }	
      

      Enabling the edit mode causes delete buttons to be visible for all cells:

      To hide delete buttons add/modify the following code

      			
          func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
              return .none
          }
          
          func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
              return false
          }	
      
    3. To enable/disable the edit mode from the Object Library drag Navigation Bar component, place it on top of existing table view and add all necessary constraints

      Add a Bar Button Item to the right of the Navigation Bar

      Select the Bar button item and in the Attributes inspector in the Title field change it to Edit

      Open The Assistant Editor and make sure the ViewController.swift file is visible. Control and drag from the Bar Button Item to the ViewController.swift class and create the editingToggle action

      Add/modify the following code

      			
          @IBAction func editingToggle(_ sender: UIBarButtonItem) {
              self.tableView.isEditing = !self.tableView.isEditing
          }	
      

      comment

      			
      	/*
          func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
              return .none
          }
          
          func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
              return false
          }*/
      

      change viewDidLoad() method from

      			
          override func viewDidLoad() {
              ...
              self.tableView.isEditing = true
              ...
          }	
      

      to

      			
          override func viewDidLoad() {
              ...
              self.tableView.isEditing = false
              ...
          }	
      

      and make a test: every time we press Edit button, we enable/disable the table view edit mode

    4. Enable the reorder control to move cells and implement the code so that the elements in the underlying data arrays are updated
      			
          func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
              let movePeakName = self.eightThousandersPeaks[sourceIndexPath.row]
              let movePeakHeight = self.eightThousandersPeaksHeight[sourceIndexPath.row]
              
              eightThousandersPeaks.remove(at: sourceIndexPath.row)
              eightThousandersPeaksHeight.remove(at: sourceIndexPath.row)
              
              eightThousandersPeaks.insert(movePeakName, at: destinationIndexPath.row)
              eightThousandersPeaksHeight.insert(movePeakHeight, at: destinationIndexPath.row)
              
              tableView.reloadData()
          }
      

    5. Optionally we can add/modify the following code to enable the reorder control only for some rows:
      			
          func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
              let detailTextLabel = self.eightThousandersPeaksHeight[indexPath.row]
              
              if let height = Int(detailTextLabel) {
                  if (height < 8500) {
                      return false;
                  } else {
                      return true;
                  }
              } else {
                  return false
              }
          }
      

  12. Step 10: delete TableView row when swipe -- preferred way (since iOS 11)
    Here is an another (and preferred) method to delete on swipe: the swipe actions. Swipe actions replace the older edit actions (yet another method than described in step 8) and are the preferred way starting with iOS 11. The edit action API is not deprecated in iOS 11 but it may be in a future release.

    1. Make a following comment
          /*
          func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle,
                         forRowAt indexPath: IndexPath)
          {
              if editingStyle == .delete
              {
                  eightThousandersPeaks.remove(at: indexPath.row)
                  eightThousandersPeaksHeight.remove(at: indexPath.row)
                  tableView.reloadData()
              }
          }
          */
      

      Now we shouldn't be able to delete by swipe.

    2. Add the following code
          func dummyAction(_ message: String) {
              let alert = UIAlertController(title: "Information",
                                            message: message,
                                            preferredStyle: .alert)
              let cancelAction = UIAlertAction(title: "Close",
                                               style: .default,
                                               handler: nil)
              
              alert.addAction(cancelAction)
              self.present(alert, animated: true)
          }
          
          func tableView(_ tableView: UITableView,
                         leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
          {
              
              let actionMove = UIContextualAction(style: .normal,
                                                     title:  "Move",
                                                     handler: { (action:UIContextualAction, view:UIView, completionHandler:(Bool) -> Void) in
                                                      
                                                      self.dummyAction("Move action")
              })
              actionMove.backgroundColor = .blue
              
              let actionEdit = UIContextualAction(style: .normal,
                                                  title:  "Edit",
                                                  handler: { (action:UIContextualAction, view:UIView, completionHandler:(Bool) -> Void) in
                                                      
                                                      self.dummyAction("Edit action")
              })
              actionEdit.backgroundColor = .green
              
              let configuration = UISwipeActionsConfiguration(actions: [actionMove, actionEdit])
              return configuration
          }
          
          func tableView(_ tableView: UITableView,
                         trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
          {
              let actionDelete = UIContextualAction(style: .normal,
                                                  title:  "Delete",
                                                  handler: { (action:UIContextualAction, view:UIView, completionHandler:(Bool) -> Void) in
                                                      
                                                      self.dummyAction("Delete action")
              })
              actionDelete.backgroundColor = .red
              
              let actionView = UIContextualAction(style: .normal,
                                                  title:  "View",
                                                  handler: { (action:UIContextualAction, view:UIView, completionHandler:(Bool) -> Void) in
                                                      
                                                      self.dummyAction("View action")
              })
              actionView.backgroundColor = .yellow
              
              let configuration = UISwipeActionsConfiguration(actions: [actionDelete, actionView])
              configuration.performsFirstActionWithFullSwipe = false
              return configuration
          }
      

    3. Please note that active option configuration.performsFirstActionWithFullSwipe = false
      			
          func tableView(_ tableView: UITableView,
                         trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
          {
              ...
              
              let configuration = UISwipeActionsConfiguration(actions: [actionDelete, actionView])
              configuration.performsFirstActionWithFullSwipe = false
              return configuration
          }			
      

      stops performing the first action in response to full swipe across the whole row.

  13. Step 11: select multiple rows
    1. Add a following code in ViewController.swift
          override func viewDidLoad() {
              ...
              self.tableView.isEditing = false
              self.tableView.allowsMultipleSelectionDuringEditing = true
              ...
          }			
      
    2. Next comment tableView:didSelectRowAt method
          /*
          func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
              ...
          }
          */			
      
    3. Add the following code
          func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
              print("=== BEGIN (select) ===")
              if let paths = tableView.indexPathsForSelectedRows {
                  for path in paths {
                      print(self.eightThousandersPeaksHeight[path.row])
                  }
              }
          }
          
          func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
              print("=== BEGIN (deselect) ===")
              if let paths = tableView.indexPathsForSelectedRows {
                  for path in paths {
                      print(self.eightThousandersPeaksHeight[path.row])
                  }
              }
          }			
      

      Now we should be able to select multiple list items

      === BEGIN (select) ===
      8611
      === BEGIN (select) ===
      8611
      8516
      === BEGIN (select) ===
      8611
      8516
      8850
      === BEGIN (deselect) ===
      8516
      8850