How to pass data between UIViewController in Swift

In this example I am going to show you how to pass data between two UIViewControls

First I am going to create single view control
File > New > Projects..
Then you select Single View Application and you can name the project as PassDataViewControl

You can see only one ViewController in your application now. Now you add another ViewController from the Object library in to your story board
Now you need to name your second ViewController. First select the left round button in your second view controller and then click on the Identity inspector panel on the right side of your XCODE editor. Then you can put “SecondViewController” for Class and Story Board id fields as shown in the following

Now I am going to create .swift file for the SecondViewController.
Go to File > New > File… and select the Swift File to create the file. You can name the file as SecondViewController

You add the following basic code for this file

Then you place UIText and UILable control in your first ViewController.
You can place UILabel control in your second view control

Once you place the controls into your ViewControllers you can add Navigation control to your ViewController. You select the first ViewController in your story board and then click Editor > Embed In > Navigation Controller

Then you create IBOutlet from UITextField in your ViewController.swift file

Now connect UIButton as action to ViewController.swift file. So your action name is “show” and inside the show method you can put the following code

Here what you are going to do is create an instance from the SecondViewController and show it

Now lets see how to pass data from the First ViewControl to SecondViewControl
I will put UILabel control on the SecondViewController and make a Outlet named labelData from it

Next I am going to create variable strDataReceived to receive data and then you can assign value of strDataReceived to labelData.text inside your viewDidLoad() function

Finally you have to add code to show method in your ViewController.swift file

Leave a Reply

Your email address will not be published. Required fields are marked *