How to Passing Data Between Controllers and Switch View Controllers in Swift?

You started to learning iOS development and you are searching one simple answer! Just passing a data one controller to different controller or want to show different controller from another controller. Let me show you!

First of all we are creating new project as always do when we starting a new tutorial.

Let’s give a name our project. I you already have a project, skip these steps until here. After naming select your project destination.

We will create new Cocoa Touch Class file. File > New > File or CMD + N

Let’s give it name too. I choose to name it SecondViewController. In this way I will explain easily.

After that, from “Main.storyboard” we are adding new View Controller. If you don’t how to add object look right up corner in XCode. You should see a plus (+) button. You can add from there.

After adding new controller your Main.storyboard should like this.

Now, we will change our view controller attributes. If you can’t any thing right of the XCode click the your black area that is up your Second View Controller (not directly view controller). In Identity tabs select your “SecondViewController”. If you can’t see your controllers name, be sure you created. AND, don’t forget to change Storyboard ID. It should not be blank. You can give anything you want but I choose to name it “Second”.

Now, it is time to code. We will create a variable to see changes. Let’s name it “secondVariable.” I know, there is too much second things.

import UIKit

class SecondViewController: UIViewController {
    var secondVariable = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        print("Second View Controller opened.")
        print(secondVariable)
    }
}

Last and most important part. Important reminder: Don’t write your into the “viewDidLoad()” instead of “viewDidAppear()”.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        print("First View Controller opened.")
    }

    override func viewDidAppear(_ animated: Bool) {
        if let secondViewController = storyboard?.instantiateViewController(withIdentifier: "Second") as? SecondViewController {
            print("Second View Controller opening")
            secondViewController.secondVariable = "Passing data from first view controller"
            present(secondViewController, animated: true, completion: nil)
        }
    }

}

This is the result that you should see it.

Leave a Reply