简体   繁体   中英

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. I am wondering how to access the 2ndViewController from the 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. Is there something I need to hook up for it to appear in the prepare for segue function?

Or is there another way to achieve this?

You need to override prepare(for segue: sender:) in the masterViewController class.

The segue needs an identifier in the storyboard. In prepare , you then check if the segue to be prepared for is the one you gave the identifier to via segue.identifier == "yourIdentifier" .

Then you can resolve the embedded ViewController as your 2ndViewController like so:

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! , you're force-unwrapping segue.destination as your 2ndViewController class. If you're not 100% certain this segue will always have that class as it's destination, consider instead using as? to treat child as optional and then doing additional checks for it's existence before attempting to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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