UITableViewController

This tutorial demonstrates common use cases for the UITableView and UITableViewController classes.

Last update: July 18, 2018 | Tested with: Xcode 9.4 and Xcode 10 Beta 4

Configure table contents using the Storyboard:
Configuring table contents using the Storyboard

Provide section and row content programmatically:
Provide section and row content programmatically

Show data from a Swift Array:
Table View with data from Swift Array

Configure cells using cell styles:
Fruits Images Cell

Using Custom cells:
Using Custom cells to customize UITableViewCells

Grouping cells into sections:
Grouping cells

Making table cells reorderable:
Reorderable/Movable table cells

Requirements

For this tutorial you need basic programming skills and know how to use Xcode. You should know everything that is in the “How to develop an iPhone app” iOS Tutorial. To develop iOS apps for the iPhone/iPad using Xcode 9, you’ll need a Mac running at least Mac OS X 10.13 High Sierra.

Creating an example project

  1. Run Xcode and create a new project with File » New » Project ⌘⇧N. Select iOS » Application » Single View Application:

    File » New » Project » iOS » Application » Single View Application
  2. Name the app “NewspaperExample”.
    Choose Swift as Language, select iPhone for Devices.

    New project settings

  3. Delete the controller class ViewController.swift that was created automatically:

    Delete ViewController.swift
  4. Open Main.storyboard, select the controller that was created automatically in the Outline and delete it with Edit » Delete so that the storyboard is completely empty:

    Delete default controller in storybord

Configure table contents using the Storyboard

  1. Drag in a new Table View Controller from the Object Library:

    Add a Table View Controller in the Storyboard
  2. Configure the controller as Initial View Controller:

    Initial View Controller
  3. Shift-Click on the table to see all objects at that position and select Table View:

    Select Table View With Shift+Click
  4. In the Attributes Inspector configure Static Cells for Content to configure the Table View cells in the storyboard instead of writing code to provide the data. Set the Style of the Table View to Grouped:

    Table View: Static Cells + Style Grouped
  5. Show the Document Outline and familiarize yourself with the object structure. The Table View Controller manages its Table View consisting of a single Table View Cell row and an empty Content View in the cell:

    Outline View for Table View Controller
  6. Select the section using the outline or with Shift + Click. Set Table Demos as Header text:

    Section Header
  7. Select the first cell and configure Basic as Style for all cells. A Basic Cell has one Label by default:

    Cell Styles
  8. Configure Basic as Style for the second cell as well and delete the third cell. Configure some label texts:

    Table Contents

  9. Run the app with ⌘R.

Provide section and row content programmatically

  1. Use the project from the previous steps or download a starter project here:
    NewspaperExample-static-cells.zip

  2. Create a new source code file in the NewspaperExample group:

    New File
  3. Choose Cocoa Touch Class for iOS:

    New iOS Cocoa Touch Class
  4. Create a subclass of UITableViewController in Swift and name it StoriesTableViewController:

    New Table View Controller Class
  5. Open the storyboard and set StoriesTableViewController as class for the Table View Controller:

    Tableviewcontroller Class
  6. Select the Table View and configure Dynamic Prototypes for Content to define a prototype for the cells in the storyboard but to provide the content in the controller class. Configure 1 prototype cell and select Plain as Style:

    Dynamic Prototypes
  7. Select the Prototype cell and configure LabelCell as Identifier. The identifier is used in the controller implementation to create cells according to the prototype from the Storyboard:

    Cell Reuse Identifier
  8. In the StoriesTableViewController class, customize the numberOfSectionsInTableView and tableView:numberOfRowsInSection: methods from the UITableViewDataSource protocol to return a fixed number of sections and rows and remove the #warning comments:

    Section and Row Counts in UITableViewDataSource
  9. Uncomment the tableView:cellForRowAtIndexPath: method in the controller class and customize it to create cells according to the Prototype cell and configure the cell text to show the section and row numbers:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
    
        cell.textLabel?.text = "Section \(indexPath.section) Row \(indexPath.row)"
    
        return cell
    }
  10. Overwrite the tableView:titleForHeaderInSection: method using the Xcode code completion:

    Overwrite tableView:titleForHeaderInSection: method

    Implement the method to return a title according to the section number:

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Section \(section)"
    }
  11. Remove the remaining code in the class, this should be the code in the class:

    import UIKit
    
    class StoriesTableViewController: UITableViewController {
    
        // MARK: - Table view data source
    
        override func numberOfSections(in tableView: UITableView) -> Int {
            return 3
        }
    
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 5
        }
    
      override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
         return "Section \(section)"
      }
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
    
            cell.textLabel?.text = "Section \(indexPath.section) Row \(indexPath.row)"
    
            return cell
        }
                   
    }

    Hint: The “// MARK: ” comment groups the methods, for example when choosing a method from the Jump Bar:

    Jumpbar Method Groups

  12. Run the app with ⌘R:

    Table showing the section and row

Show data from a Swift Array

  1. Use the project from the previous steps or download a starter project here:
    NewspaperExample-dynamic_prototypes.zip

  2. Add a type Headline to hold some example data and add an Array with a few example headline values to the StoriesTableViewController:

    import UIKit
    
    struct Headline {
    
        var id : Int
        var title : String
        var text : String
        var image : String
    
    }
    
    class StoriesTableViewController: UITableViewController {
    
        var headlines = [
        Headline(id: 1, title: "Lorem Ipsum", text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", image: "Apple"),
        Headline(id: 2, title: "Aenean condimentum", text: "Ut eget massa erat. Morbi mauris diam, vulputate at luctus non.", image: "Banana"),
        Headline(id: 3, title: "In ac ante sapien", text: "Aliquam egestas ultricies dapibus. Nam molestie nunc.", image: "Cantaloupe"),
    ]
    
        // MARK: - Table view data source
        
        // ...
    
    }
  3. Customize the StoriesTableViewController to use data from the Array:

    class StoriesTableViewController: UITableViewController {
    
        // ...
        
        // MARK: - Table view data source
    
        override func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
    
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return headlines.count
        }
        
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
            
            cell.textLabel?.text = headlines[indexPath.row].title
            
            return cell
        }
        
    }

    Hint: You can also remove the numberOfSections method - by default tables have one section.

  4. Run the app with ⌘R:

    Table View with data from Swift Array

Configure cells using cell styles

  1. Use the project from the previous steps or download a starter project here:
    NewspaperExample-table_swift_array.zip

  2. There are four different types of cell styles that have views out of the box - Basic, Left/Right Detail and Subtitle:

    UITableViewController Cell Styles

  3. For the StoriesTableViewController in the storyboard, select the prototype cell and set the style Subtitle:

    Cell Styles
  4. Set a row height of 60 for the cell:

    Cell Styles
  5. Download fruit-images.zip and drag the uncompressed folder fruit-images to the Assets.xcassets in your project:

    Fruits Assets

  6. Extend the implementation of tableView(cellForRowAt:) in StoriesTableViewController to show a detail text and an image (all cells have an optional imageView that is created when the property is accessed):

    class StoriesTableViewController: UITableViewController {
    
        ...
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
    
            let headline = headlines[indexPath.row]
    cell.textLabel?.text = headline.title
    cell.detailTextLabel?.text = headline.text
    cell.imageView?.image = UIImage(named: headline.image)
    
            return cell
        }
    
    }
  7. Run the app and check that the table looks like this:

    Fruits Images Cell

Example code

You can download the finished example project here:
NewspaperExample-cell_styles.zip

More UITableViewController tutorials

Using Custom cells:
Using Custom cells to customize UITableViewCells

Grouping cells into sections:
Grouping cells

Making table cells reorderable:
Reorderable/Movable table cells

More information

Btn read 3c0e607615 iOS Developer Blog
Btn subscribe 930758687e Subscribe: Email · Twitter
Btn training bbbdf557d2 Next iOS training: 19. - 23. November 2018, Hamburg
Btn about 5378472193 About me · Contact