I have a storyboard set up in XCode and have a MainViewController. In the MainViewController I have added a ContainerView which naturally creates a Segue with another VIewCo
This is pretty much the same answer as the one by rdelmar only in Swift.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let embeddedVC = segue.destinationViewController as? MyEmbeddedController where segue.identifier == "EmbedSegue" {
embeddedVC.labelString = self.stringToPass
}
}
"EmbedSegue"
has to the segue identifier you set in Interface Builder.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure your segue name in storyboard is the same as this line
if ([[segue identifier] isEqualToString:@"YOUR_SEGUE_NAME_HERE"])
{
// Get reference to the destination view controller
YourViewController *vc = [segue destinationViewController];
// Pass any objects to the view controller here, like...
[vc setMyObjectHere:object];
}
}
I should also mention that because you are using a Container view, prepareForSegue
will be triggered when you'll present the ViewController
that holds the Container.
Answer for Swift 4:
if let controller = segue.destinationController as? MyEmbeddedController, segue.identifier!.rawValue == "EmbedSegue" {
controller.labelString = self.stringToPass
}
You can use prepareForSegue just like any other two controllers -- that method will be called after the two controllers are instantiated, but before either viewDidLoad runs. The other way to do this is to use the parent controller's childViewControllers property (the embedded controller is a child). So, the child will be self.childViewControllers[0].
After Edit:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"EmbedSegue"]) {
MyEmbeddedController *embed = segue.destinationViewController;
embed.labelString = self.stringToPass;
}
}
Of course, you have to change the names to what you have. Make sure the name you give to the segue in IB matches the one you check for in the if statement. In this example labelString is a string property you set up in your embedded controller. Then in that controller's viewDidLoad method, you can set the value of the label with that string.