简体   繁体   中英

Accessing Container view controller from parent controller in Swift 2

I want to access label of container view controller from parent view controller. I have tried the following:

prepareForSegue is a function in parent view controller. ViewController2 is the container view controller. parin2 is the name of the label in the container view controller.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!)
{
    let vc1 = segue.destinationViewController as! ViewController2;
    vc1.parin2.text=String("helo");
}

This gives the following error:

fatal error: unexpectedly found nil while unwrapping an Optional value

You didn't say exactly which line caused the error, but my guess is that it was let vc1 = segue.destinationViewController as! ViewController2 let vc1 = segue.destinationViewController as! ViewController2 (by the way, please omit the ';'s in Swift). The as! appears to be failing because the destination view controller isn't a ViewController2 . To verify this, set a breakpoint on that line, then examine the segue's destinationViewController property to see what kind of view controller it is. If it's not a ViewController2 , then the problem is in your storyboard. Either you're getting a segue that you didn't expect, or the class of the destination in the storyboard isn't a ViewController2 .

A better pattern for handling prepareForSegue is the following:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    // ALWAYS check the segue identifier first! If you forgot to put one on
    // your segue in the storyboard, then you should see a compiler warning.
    switch segue.identifier {
    case "SegueToViewController2":
        guard let destination = segue.destinationViewController as? ViewController2 else {
            // handle the error somehow
            return
        }
    default:
        // What happens when the segue's identifier doesn't match any of the
        // ones that you expected?
    }
}

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