3.2. Send data from Screen 1 (ViewController) to Screen2 (ShowViewController)

Now it's time to send data from our first screen (ViewController) to the second screen (ShowViewController). Remember, we created a variable named messageFromFirstScreen? We have to access that variable from the first screen (ViewController) and set the text the user puts in textFieldMessage to messageFromFirstScreen.

So, let's get back to ViewController.swift. Scroll down to the button event action method onButtonSendTapped(). And add the following code in onButtonSendTapped() after we initialize the ShowViewController:

//
//  ViewController.swift
//  App3
//
//  Created by Sakib Miazi on 5/10/23.
//
// MARK: On button tapped...
    @objc func onButtonSendTapped(){
        //initializing a new screen with ShowViewController...
        var showViewController = ShowViewController()
        
        //set the message to ShowViewController's messageFromFirstScreen variable...
        if let unwrappedMessage = textFieldMessage.text{
            if !unwrappedMessage.isEmpty{ // checking if the user has put any message...
                //Sending data...
                showViewController.messageFromFirstScreen = unwrappedMessage
                
                //push the screen to Stack...
                navigationController?.pushViewController(showViewController, animated: true)
            }else{
                //Alert the user to put message....
            }
            
        }
    }

Now let's run the code:

So, we can see that we can send data from one screen to the next.

Last updated

Was this helpful?