[英]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. prepareForSegue是父视图控制器中的函数。 ViewController2 is the container view controller.
ViewController2是容器视图控制器。 parin2 is the name of the label in the container view controller.
parin2是容器视图控制器中标签的名称。
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
let vc1 = segue.destinationViewController as! ViewController2
(by the way, please omit the ';'s in Swift). let vc1 = segue.destinationViewController as! ViewController2
(顺便说一下,请在Swift中省略';')。 The as!
as!
appears to be failing because the destination view controller isn't a ViewController2
. 似乎由于目标视图控制器不是
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. 要验证这一点,请在该行上设置一个断点,然后检查segue的
destinationViewController
属性,以查看它是哪种视图控制器。 If it's not a ViewController2
, then the problem is in your storyboard. 如果不是
ViewController2
,那么问题出在您的情节提要中。 Either you're getting a segue that you didn't expect, or the class of the destination in the storyboard isn't a ViewController2
. 要么您得到了意外的提示,要么情节
ViewController2
中的目标类别不是ViewController2
。
A better pattern for handling prepareForSegue
is the following: 更好的处理
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.