Reputation: 228
I use this code for go to new story board and pass variable X to a viewController in new storyboard
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let homeViewController: UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewControllerCall")
homeViewController.myVar = "x"
self.present(homeViewController, animated: true, completion: nil)
But I get this error:
Value of type 'UIViewController' has no member 'myVar'
Upvotes: 2
Views: 4619
Reputation: 8376
In this line:
let homeViewController: UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewControllerCall")
You are saying "Instantiate a view controller from the storyboard, and infer its type to be a UIViewController
". However, what you need to do is specifying it as ViewControllerCall
.
You can do this by type casting - adding as? ViewControllerCall
. (Or as! ViewControllerCall
, if you don't want to use the if let
clause).
Your code should look like this:
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
if let homeViewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewControllerCall") as? ViewControllerCall {
homeViewController.myVar = "x"
self.present(homeViewController, animated: true)
}
Or
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let homeViewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewControllerCall") as! ViewControllerCall
homeViewController.myVar = "x"
self.present(homeViewController, animated: true)
Note that by using as!
in the second way I've presented, it will crash your app if the view controller with identifier ViewControllerCall
is not of type ViewControllerCall.
Upvotes: 6
Reputation: 352
You have to change second line code only. 1. Go to your Main storyboard and check the class for ViewController for which you want to pass variable and set storyboard identifier same as class name. 2. Now if your class name is "ViewControllerCall" then change your line code as below:
let homeViewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewControllerCall") as! ViewControllerCall
Upvotes: 0