Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a Container View that I popped into my storyboard. There's a wonderful little arrow that represents the embed segue to another scene. That scene's top level object is controlled by a custom UIViewController. I want to call a method that's implemented in my custom class. If I have access to the container, how do I get a reference to what's inside?

like image 423
Evan Conrad Avatar asked Apr 11 '15 19:04

Evan Conrad


People also ask

What is container view iOS?

Unlike a content view controller that displays your app's data, a container view controller displays other view controllers, arranging them onscreen and handling navigation between them. A container view controller is still a view controller, so you display it in a window or present it like any other view controller.


1 Answers

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!

like image 186
ABakerSmith Avatar answered Sep 18 '22 22:09

ABakerSmith