Pass Data Between View Controllers iOS Tutorial

Data can be passed between view controllers using a segue. In this tutorial a number from a collection view cell will be passed to a label on a new view controller. This tutorial is made with Xcode 10 and built for iOS 12.

Project Setup

Open Xcode and create a new Single View App.

For product name, use IOSPassDataViewControllerTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Storyboard Setup

Go to the storyboard. Remove the View Controller from the Storyboard and drag a Collection ViewController to the Scene. Select the View Controller and go to the Editor Menu. Select Embed In -> Navigation Controller.

Select the Navigation Controller and go to The Attribute inspector. In the View Controller section check the "Is Initial View Controller" checkbox.

Select The Collection View and go the Size inspector. In the Collection View section change the Cell Size to a width and height of 100 points.

Drag a Label from the Object Library and place it on the Center of the Collection View Cell.

Select the Label and go to the Attribute inspector. In the View section set the Tag value to 100.

Select the Collection View Cell and go to the Atrribute inspector. In the Collection Reusable View section set the Identifier to "Cell".

The storyboard will look like this.

Since the View Controller is removed from the Storyboard the ViewController.swift file can also be deleted from the project. Add a new file to the project, select iOS -> Source -> Cocoa Touch Class. Name it CollectionViewController and make it a subclass of UICollectionViewController.

The CollectionViewController class needs to be linked to The Collection View Controller object in the Storyboard. Select it and go the Identity Inspector. In the Custom Class section change the class to CollectionViewController

Code Implementation 

Go to CollectionViewController.swift file and enter the following line.

let modelData = ["1","2","3","4","5","6","7","8","9"]

With the creation of the CollectionViewController class, most delegate methods are already implemented. Some methods must be tweaked a little. Change the following methods.

override func numberOfSections(in collectionView: UICollectionView) -> Int {
        // 1
        return 1
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 2
        return modelData.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
    
        // Configure the cell
        // 3
        if let label = cell.viewWithTag(100) as? UILabel {
            label.text = modelData[indexPath.row]
        }
    
        return cell
    }
  1. By default the CollectionView only has 1 section.

  2. The number of cells is equal to the number of items in the modelData array.

  3. The text of the label is set to the current index of the modelData array.

Build and Run the project.

Add Segue to View Controller

The number value of the collection view cell will be passed to a new View Controller. Open the Storyboard and drag this View Controller to the right side of the Collection View Controller. Drag a Label onto the View Controller.

The data will be passed using a segue. Drag from the Collection View Cell to the View Controller and select the Show segue.

Add a new file to the Project. select iOS -> Source -> Cocoa Touch Class. Name it DetailViewController and make it a subclass of ViewController. Go to the Storyboard, select the View Controller and go the Identity Inspector. In the Custom Class section change the class to DetailViewController.

Select the Assistant Editor and make sure the DetailViewController.swift is visible. Ctrl and drag from the Text View to the DetailViewController class and create the following Outlet

Go to the DetailViewController.swift file and add the following property.

var selectedNumber: String!

Change the viewDidLoad() method to

override func viewDidLoad() {
    super.viewDidLoad()

    detailLabel.text = selectedNumber
}

Go back to the CollectionViewController.swift file and add the prepare(for:sender:) method

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as?
        DetailViewController, let index =
        collectionView.indexPathsForSelectedItems?.first {
        destination.selectedNumber = modelData[index.row]
    }
}

This method notifies the view controller that a segue is about to be performed. Inside the selected cell the corresponding number from the modeldata array will be assigned to the selecedNumber property in the DetailViewController class.

Run Project

Build and Run the project and select a cell. the number will be passed through and displayed on the Detail View Controller.

You can download the source code of the IOSPassDataViewControllerTutorial at the ioscreator repository on Github

Related Articles