本文介绍了如何在Swift中获取容器内的视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个容器视图,我弹出了我的故事板。有一个很棒的小箭头代表嵌入到另一个场景的segue。该场景的顶级对象由自定义 UIViewController 控制。我想调用一个在我的自定义类中实现的方法。如果我有权访问容器,我如何获取对内部的引用?

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?

推荐答案

您可以使用 prepareForSegue UIViewController 中的一个方法,可以访问任何被隐藏的 UIViewController 从您当前的视图控制器,这包括嵌入 segues。

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.

关于 prepareForSegue 的文档:

在你的问题中你提到需要调用一个自定义视图控制器上的方法。以下是如何执行此操作的示例:

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。为嵌入segue提供标识符。您可以在界面生成器中执行此操作,方法是选择您的segue,转到属性编辑器并查看 Storyboard Embed Segue

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。创建类如下的类:

引用保持为 embeddedViewController 所以 myMethod 。它被声明为一个隐式解包的可选项,因为给它一个非零的初始值是没有意义的。

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. 设置 UIViewControllers的类在IB中使用 Identity Inspector 。例如:

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

现在一切都应该有效。希望有所帮助!

And now everything should work. Hope that helps!

这篇关于如何在Swift中获取容器内的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 07:19