繁体   English   中英

在Swift 2中从父控制器访问Container视图控制器

[英]Accessing Container view controller from parent controller in Swift 2

我想从父视图控制器访问容器视图控制器的标签。 我尝试了以下方法:

prepareForSegue是父视图控制器中的函数。 ViewController2是容器视图控制器。 parin2是容器视图控制器中标签的名称。

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

这给出了以下错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

你没有说具体行造成的错误,但我的猜测是,它let vc1 = segue.destinationViewController as! ViewController2 let vc1 = segue.destinationViewController as! ViewController2 (顺便说一下,请在Swift中省略';')。 as! 似乎由于目标视图控制器不是ViewController2而失败。 要验证这一点,请在该行上设置一个断点,然后检查segue的destinationViewController属性,以查看它是哪种视图控制器。 如果不是 ViewController2 ,那么问题出在您的情节提要中。 要么您得到了意外的提示,要么情节ViewController2中的目标类别不是ViewController2

更好的处理prepareForSegue模式如下:

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?
    }
}

暂无
暂无

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

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