Passing Data Between View Controllers Using Properties In iOS

Whenever you create multiple view controllers, you'll need to pass data from one view controller to another view controller in any situation. There are many ways to pass data from one view controller to another. Today we're going to learn simple method to pass data using Properties. Let's get started.

Properties are the variables, every instance of the class have property so that you can easily pass the data just by creating the instance of destination view controller and assigning the values to the properties of destination view controller.


Steps : 

  • Create new Xcode project. Then change the default ViewController name into FirstViewController(CMD + click via tracpad - > Rename)
  • Drag and drop another view controller from Object Library into Interface Builder
  • Then create a new View Controller Swift file for SecondViewController
  • Drag and drop label, textfield and button into FirstViewController. Also drag another label for SecondViewController to display the data from FirstViewController

FirstViewController :

import UIKit

class FirstViewController: UIViewController {
    
    var data: String? = ""
    @IBOutlet weak var dataField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
    }

    @IBAction func buttonTapped(_ sender: UIButton) {
        if dataField.text != "" {
            data = dataField.text!
        } else {
            print("Please enter any data in textField to pass the data from current vc to next vc")
        }
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SecondVC") as! SecondViewController
        vc.textVal = data!  //Assigning data for second view controller
        present(vc, animated: true, completion: nil)
    }
}



SecondViewController :

import UIKit

class SecondViewController: UIViewController {

    var textVal: String = ""
    @IBOutlet weak var txtLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        txtLabel.text = textVal
    }
    @IBAction func goToFirstVC(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
}

See you in the next tutorial...

Vinoth Vino