Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Data to a ViewController created using instantiateViewControllerWithIdentifier?

I've created an app that uses a bunch load of Container views. Today i've found out that embedded segues are not supported in iOS 5 (thanks Xcode for letting me know.) So right now I have a lot of embedded segues that passes data between one another.

I'm using this code to load ViewControllers inside a UIView instead of the Container from the IB:

RootViewController:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    NewsViewController *news = [storyboard instantiateViewControllerWithIdentifier:@"NewsViewControllerID"];
    news.view.frame = self.newsSection.bounds;
    [self.newsSection addSubview:news.view];
    [self addChildViewController:news];
    [news didMoveToParentViewController:self];
    // Do any additional setup after loading the view.
}

How can I use the above and still pass data to NewsViewController (something like prepare for segue)

I've tried inserting in the above something like

        NewsViewController *news = [storyboard instantiateViewControllerWithIdentifier:@"NewsViewControllerID"];
        news.view.frame = self.newsSection.bounds;
        news.myLabel.text = @"Test";
        [self.newsSection addSubview:news.view];

But the label won't change.

I prefer just to pass the data and not use a singleton or delegation.

Thanks

like image 917
Segev Avatar asked Mar 25 '26 19:03

Segev


1 Answers

I would recommend creating a public method, from where you could pass the data you need on your NewsViewController controller. Still, the issue right now is that the you are updating the UI before it has been initialised. Also I would recommend you to have a look on how to create content UIViewControllers, because right now you are only adding its UIView. Check this document from Apple, look at the section Implementing a Custom Container View Controller. And this part of the code:

- (void) displayContentController: (UIViewController*) content;
{
   [self addChildViewController:content];                 // 1
   content.view.frame = [self frameForContentController]; // 2
   [self.view addSubview:self.currentClientView];
   [content didMoveToParentViewController:self];          // 3
}

So in your case, after the step 3 has been made, you could pass the values you want to use inside your NewsViewController.

like image 183
Rui Peres Avatar answered Mar 28 '26 08:03

Rui Peres



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!