How do I pass data from my ViewController to a Con

2019-02-04 11:04发布

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 VIewController.

In my MainViewController.m file I have set up data and want to link this data to a label in the ContainerView however I thought I could click on the File's Owner and do this but of course I can't because they are 2 different viewcontrollers now.

Can someone please help me because I'm struggling with this. There must be an easy way but I can't crack it!

Thank you

4条回答
ゆ 、 Hurt°
2楼-- · 2019-02-04 11:41

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.

查看更多
Anthone
3楼-- · 2019-02-04 11:43

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.

查看更多
姐就是有狂的资本
4楼-- · 2019-02-04 11:58

Answer for Swift 4:

if let controller = segue.destinationController as? MyEmbeddedController, segue.identifier!.rawValue == "EmbedSegue" {
    controller.labelString = self.stringToPass
}
查看更多
爷、活的狠高调
5楼-- · 2019-02-04 12:00
- (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.

查看更多
登录 后发表回答