Reputation: 3047
I am using Swift. I have 2 ViewControllers a) ParentVC & b) ChildVC. When I instantiate the chidVC, I want to pass some data from Parent to Child. Not sure how. Below is the code
ParentVC
override func viewDidLoad() {
let controller = storyboard?.instantiateViewControllerWithIdentifier("ChildViewController") as UIViewController!
//I want to pass some value - For example: controller.id = 3
addChildViewController(controller)
containerView.addSubview(controller.view)
didMoveToParentViewController(controller)
}
Within Child VC
var id: Int?
P.S: I definitely want to use "instantiateViewControllerWithIdentifier". I have seen Passing Data Between View Controllers, but thats in ObjC and I am looking for code in Swift as I don't know how to translate it. Also I don't want to use prepareForSegue.
Upvotes: 1
Views: 3070
Reputation: 1147
pass the ID after instantiating
let controller = storyboard?.instantiateViewControllerWithIdentifier("ChildViewController") as YourViewController!
controller.yourID = 100
presentViewController(controller, animated:true, completion:nil)
Upvotes: 3
Reputation: 948
You almost had it. In the instantiation of your ChildViewController you need cast into the class of your ChildViewController not UIViewController, because UIViewController does not have the property.
so replace
let controller = storyboard?.instantiateViewControllerWithIdentifier("ChildViewController") as UIViewController!
by
let controller = storyboard?.instantiateViewControllerWithIdentifier("ChildViewController") as YourChildViewControllerClass!
Edit:
Now you can set the property like truongky answered:
controller.yourId = 100
Upvotes: 1