How to pass data between screens in iOS Swift (Forward)

1. Using programatically

to implement this method we are considering we have one viewcontroller in storyboard having identifier

//FirstViewController

import UIKit

class FirstViewController: UIViewController {
    
    var myName = "Sandesh"
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func btnNext(_ sender: AnyObject) {
        
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
        vc.myFirstName = myName
        navigationController?.pushViewController(vc, animated: true)        
    }    
}
//SecondViewController

import UIKit

class SecondViewController: UIViewController {
    
    var myFirstName: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        print(myFirstName)
    }

2. Using Segue 

we are considering that we are moving from one screen to another using segue

//FirstViewController 

import UIKit

class FirstViewController: UIViewController {
    
    var myName = "Sandesh"    

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.destination is SecondViewController {
                let vc = segue.destination as! SecondViewController
                vc.myFirstName = myName
            }
        }
    }
}

Detailed resources :

https://matteomanferdini.com/how-ios-view-controllers-communicate-with-each-other/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s