Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIViewController viewWillAppear not called when adding as subView

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?

like image 451
Fogmeister Avatar asked Aug 14 '13 15:08

Fogmeister


People also ask

Why does viewWillAppear not get called when an app comes back from the background?

The Simple Answer The technical reason for when viewWillAppear gets called is simple. Notifies the view controller that its view is about to be added to a view hierarchy. It can't be any view hierarchy — it has to be the one with a UIWindow at the root (not necessarily the visible window).

Does viewWillAppear get called before viewDidLoad?

viewWillAppear(_:)Always called after viewDidLoad (for obvious reasons, if you think about it), and just before the view appears on the screen to the user, viewWillAppear is called.

How many times is viewWillAppear called?

If both these methods are called, what's the difference between the two? viewDidLoad() is only called once, when the view is loaded from a . storyboard file. viewWillAppear(_:) is called every time the view appears.

What happens between viewWillAppear and viewDidAppear?

There is a noticeable pause after row selection and before the new view is pushed. Some logging indicates that all of my code is reasonably quick, from row selection until the pushed controller's viewWillAppear . But then the time between viewWillAppear and viewDidAppear is logged at around 0.7 seconds.


1 Answers

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.

like image 85
rdelmar Avatar answered Oct 01 '22 03:10

rdelmar