ios - 如何在 Swift 中获取容器内的 View ?

标签 ios swift uicontainerview

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

最佳答案

您可以使用 prepareForSegue(UIViewController 中的一种方法)从您当前的 View Controller 访问任何 UIViewController,这包括 embed segues。

来自关于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.

在您的问题中,您提到需要在您的自定义 View Controller 上调用一个方法。以下是您如何做到这一点的示例:

1. 为您的嵌入 segue 提供一个标识符。您可以在 Interface Builder 中执行此操作,方法是选择您的 segue,转到 Attributes Editor 并在Storyboard Embed Segue 下查看

enter image description here

2. 创建类如下:

保留对 embeddedViewController 的引用,以便以后可以调用 myMethod。它被声明为一个隐式展开的可选值,因为给它一个非零的初始值是没有意义的。

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

enter image description here

现在一切都应该正常了。希望对您有所帮助!

关于ios - 如何在 Swift 中获取容器内的 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29582200/

相关文章:

swift - 什么时候用xib,什么时候用ContainerView?

ios - 如何通过 Swift 中的 ContainerView 更改 TableView 中项目的属性?

ios - 在 Swift 2 (Metal) 中加载 STL 对象

ios - 所有 View 的监听器

ios - 在 HMEventTrigger 启用触发器中显示错误

ios - Swift 没有看到带有可变参数的 Objective-C 方法

ios - Swift URLSession 完成处理程序

ios - 更改框架后 UIContainerView 停止接收触摸

ios - 是否可以在不停止之前任务的情况下同时使用多个模拟器进行调试?

swift - 由于 'internal' 保护级别而无法访问