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

自闭症网瘾萝莉.ら 提交于 2019-11-27 11:28:50

问题


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?


回答1:


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.

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:

And now everything should work. Hope that helps!




回答2:


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).



来源:https://stackoverflow.com/questions/29582200/how-do-i-get-the-views-inside-a-container-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!