How do I get the views inside a container in Swift? How do I get the views inside a container in Swift? ios ios

How do I get the views inside a container in Swift?


You can use prepareForSegue, a method in UIViewController, to gain access to any UIViewController being segued to from your current view controller, this includes embed segues.

From the documentation about prepareForSegue:

The default implementation of this method does nothing. Your view controller overrides this method when it needs to pass relevant data to the new view controller. The segue object describes the transition and includes references to both view controllers involved in the segue.

In your question you mentioned needing to call a method on your custom view controller. Here's an example of how you could do that:

1. Give your embed segue a identifier. You can do this in the Interface Builder by selecting your segue, going to the Attributes Editor and looking under Storyboard Embed Segue.

enter image description here

2. Create your classes something like:

A reference is kept to embeddedViewController so myMethod can be called later. It's declared to be an implicitly unwrapped optional because it doesn't make sense to give it a non-nil initial value.

//  This is your custom view controller contained in `MainViewController`.class CustomViewController: UIViewController {    func myMethod() {}}class MainViewController: UIViewController {    private var embeddedViewController: CustomViewController!    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {        if let vc = segue.destination as? CustomViewController,                    segue.identifier == "EmbedSegue" {            self.embeddedViewController = vc        }    }    //  Now in other methods you can reference `embeddedViewController`.    //  For example:    override func viewDidAppear(animated: Bool) {        self.embeddedViewController.myMethod()    }}

3. Set the classes of your UIViewControllers in IB using the Identity Inspector. For example:

enter image description here

And now everything should work. Hope that helps!


ABaker's answer gives a great way for the parent to learn about the child. For code in the child to reach the parent, use self.parent (or in ObjC, parentViewController).