简体   繁体   English

iOS ViewController调用容器内的子ViewController

[英]ios viewcontroller to call child viewcontroller inside container

I have a masterViewcontroller with the container on it and a 2ndViewController embeded via storyboard in that. 我有一个masterViewcontrollercontainer上和2ndViewController通过故事板在包埋。 I am wondering how to access the 2ndViewController from the masterViewController . 我想知道如何从masterViewController访问masterViewController

I have seen about using prepare for segue but this doesn't seem to get called for when my viewController in the container is shown. 我已经看到了关于使用prepare for segue的信息,但是当显示容器中的viewController时似乎并没有要求这样做。 Is there something I need to hook up for it to appear in the prepare for segue function? 我需要挂钩以使其出现在准备segue功能中吗?

Or is there another way to achieve this? 还是有另一种方法来实现这一目标?

You need to override prepare(for segue: sender:) in the masterViewController class. 您需要在masterViewController类中重写prepare(for segue: sender:)

The segue needs an identifier in the storyboard. segue需要情节提要中的标识符。 In prepare , you then check if the segue to be prepared for is the one you gave the identifier to via segue.identifier == "yourIdentifier" . prepare ,然后检查要准备的segue是否是您通过segue.identifier == "yourIdentifier"赋予标识符的segue.identifier == "yourIdentifier"

Then you can resolve the embedded ViewController as your 2ndViewController like so: 然后可以将嵌入式ViewController解析为2ndViewController如下所示:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    if segue.identifier == "yourIdentifier" { 
        let child = segue.destination as! 2ndViewController
    }
}

By the way, if you use as! 顺便说一句,如果您as! , you're force-unwrapping segue.destination as your 2ndViewController class. ,你力展开segue.destination为您2ndViewController类。 If you're not 100% certain this segue will always have that class as it's destination, consider instead using as? 如果您不能100%地确定此segue始终将该类作为目的地,请考虑使用as? to treat child as optional and then doing additional checks for it's existence before attempting to use it. child视为可选项,然后在尝试使用子级之前对其进行其他检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM