How to provide an argument to a view controller in containment?

41 Views Asked by At

I'm trying to pass an argument to a view controller in containment:

let childVC = ChildViewController()
addChild(childVC)
childVC.view.frame = frame
view.addSubview(childVC.view)
childVC.didMove(toParent: self)

ChildViewController has multiple properties, one of which has to be passed on from the parent view controller.

I've tried a few things, but none worked:

let childVC = ChildViewController(someProperty: someProperty)

or

let childVC = ChildViewController()
childVC.someProperty = someProperty
1

There are 1 best solutions below

1
On BEST ANSWER

This line:

let childVC = ChildViewController()

Is almost always wrong. That will create an empty instance of ChildViewController with no views, outlets, or actions set up.

Generally you want to instantiate a view controller from a Storboard or a nibfile.

If you are asking how you install contents in a child view controller's views, the answer is "Don't do that."

If you want your parent view controller to have a child view controller, the easiest way to do that is to put a container view on the parent view controller in IB. Then control-drag from that container view onto the view controller you want to be a child, and when prompted, select "embed segue" as the type of link you want to create.

That will cause the system to install the child view controller in the container view and hook up all the plumbing to make it work

The parent view controller's prepare(for:sender:) method will be called right after the child view controller is instantiated, but before it's views are loaded. You can put code in your prepare(for:sender:) method to pass values to the child view controller (not set it's views directly, but set properties or call methods)