Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...