1

I'm trying to pass data to the second view controller without success,
This is my code:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: “secondVC")
self.present(vc, animated: true, completion: nil)

//The following solution as I checked in the previous questions doesn't work:

vc.Var1InSecondViewController = self.var1
vc.Var2InSecondViewController = self.var2


It claims that 'vc' which is related to the second view controller has no member of 'Var1InSecondViewController' even though I did created it in the second view controller.

Your help would be appreciated, thank you.

Krunal
  • 77,632
  • 48
  • 245
  • 261
Shlomi
  • 337
  • 1
  • 6
  • 19
  • Add code for second view controller, with deceleration of vc.Var1InSecondViewController – Krunal Oct 04 '17 at 17:51
  • @Krunal I mention in my question that I already did that: "even though I did created it in the second view controller" – Shlomi Oct 04 '17 at 17:59
  • an answer to this question need class name for second view controller and parameters access level for your variables in second view controller. Look at Bharath's answer, It may be correct but View controller class name is missing there only. – Krunal Oct 04 '17 at 18:01

2 Answers2

3

You have to specify the class name of the secondVC as follows in order to access its properties,

Instead of,

let vc = storyboard.instantiateViewController(withIdentifier: “secondVC")

Use

let vc = storyboard.instantiateViewController(withIdentifier: “secondVC") as? YOUR_SECOND_VIEW_CONTROLLER_CLASS_NAME

And do the assignment steps before presenting the view controller as follows,

vc?.Var1InSecondViewController = self.var1
vc?.Var2InSecondViewController = self.var2
self.present(vc!, animated: true, completion: nil)
Krunal
  • 77,632
  • 48
  • 245
  • 261
Bharath
  • 2,064
  • 1
  • 14
  • 39
0

You can use this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "yourSegue" {
        if let firstViewController = segue.destination as? FirstViewController {
          firstViewController.var1 = var1
        }
    }
}
}
acoustickat
  • 39
  • 1
  • 6