Fogmeister Fogmeister - 3 months ago 27
Objective-C Question

UIViewController viewWillAppear not called when adding as subView

I have a

UIViewController
that I am loading from inside another view controller and then adding it's 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

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.