Reputation: 12228
MyViewController *myVC = (MyViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];
[scrollView addSubview:myVC.view];
The above code works, it loads a view controller that I have in my storyboard with the Storyboard ID of: "MyViewController" and displays it as a sub view.
The only thing is that I'd like to, for example, set a UILabel's text on that View Controller BEFORE doing addSubview.
Like this:
MyViewController *myVC = (MyViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];
myVC.aTextLabel.text = @"pippo";
[scrollView addSubview:myVC.view];
However, this does not work. The UILabel is empty. - I can't do anything with the view until AFTER I do addSubview. Like this:
MyViewController *myVC = (MyViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];
[scrollView addSubview:myVC.view];
myVC.aTextLabel.text = @"pippo";
The above works but it isn't pretty, the label's text is changed after the view has been added!
When I used to do this without Storyboards I would do this:
MyViewController *myVC = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
myVC.aTextLabel.text = @"pippo";
[scrollView addSubview:myVC.view];
Which would work fine.
The view that I am displaying is not being connected to other views via seque, I am loading multiple instances of it into a UIScrollView, side by side, so I was hoping that the easiest method would be something similar to the above.
So, how can I instantiate the view programmatically, update a UILabel on that view, and then add it as a subview?
Upvotes: 0
Views: 2884
Reputation: 17143
So the issue is that although the view controller is created (allocated and initialized), its view hierarchy is not loaded until someone references its view property.
So when you read myVc.view
(which is really [myVc view]
), that causes the view controller to load its views from the storyboard if they haven't been loaded already.
You may need to consider your design here. Creating a view controller, just to take its views and add them to some other view hierarchy is not a good idea unless you do it within the framework of the container view controller APIs.
Check out "Creating Custom Container View Controllers" in the View Controller Programming Guide if you want to combine several view controllers together on screen at once.
Upvotes: 2