Reputation: 163
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
Upvotes: 0
Views: 726
Reputation: 13903
You didn't say exactly which line caused the error, but my guess is that it was 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?
}
}
Upvotes: 1