UIViewController viewWillAppear not called when adding as subView

Fogmeister picture Fogmeister · Aug 14, 2013 · Viewed 35.8k times · Source

I have a UIViewController that I am loading from inside another view controller and then adding its view to a UIScrollView.

self.statisticsController = [self.storyboard instantiateViewControllerWithIdentifier:@"StatisticsViewController"];
self.statisticsController.match = self.match;

[self.scrollView addSubview:self.statisticsController.view];

I've put breakpoints in the statistics view controller and viewDidLoad is being called but viewWillAppear isn't.

Is it because I'm not pushing it onto the hierarchy or something?

Answer

rdelmar picture rdelmar · Aug 14, 2013

You should add statisticsController as a child view controller of the controller whose view you're adding it to.

self.statisticsController = [self.storyboard instantiateViewControllerWithIdentifier:@"StatisticsViewController"];
self.statisticsController.match = self.match;

[self.scrollView addSubview:self.statisticsController.view];
[self addChildViewController:self.statisticsController];
[self.statisticsController didMoveToParentViewController:self];

I'm not sure this will make viewDidAppear get called, but you can override didMoveToParentViewController: in the child controller, and that will be called, so you can put any code that you would have put in viewDidAppear in there.