ViewWillAppear not called for subview controller

I have an odd case - a view controller that creates its own view in loadView and which is then added to an existing view.

Here is the code that creates and adds VC:

 self.doneButtonViewController = [[DoneButtonViewController alloc] init]; [self.view addSubview:self.doneButtonViewController.view]; 

This code is executed in the viewDidLoad "parent" VC.

It is odd that the added VC's viewWillAppear method is never called (and is not equal to viewDidAppear ), but the added VC's viewWillDisappear method is called (at the appropriate time), as one expected.

Any clue on why viewWillAppear not called?

+8
ios cocoa-touch uiviewcontroller
source share
2 answers

The app is not aware of the subview view controller, if you do, you need to enter a view controller locator to control the root view controller. This will handle any events like this.

Since loadView could be called more than once before iOS 6, I would advise creating a view controller in init and then adding a subview to loadView . It should be like this:

 - (id)init { ... self.doneButtonViewController = [[DoneButtonViewController alloc] init]; [self addChildViewController:self.doneButtonViewController]; [self.doneButtonViewController didMoveToParentViewController:self]; ... } - (void)loadView { ... [self.view addSubview:self.doneButtonViewController.view]; ... } 

See “Implementing a container view controller” at http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/Reference/Reference.html

+15
source share

As for me, adding a child view controller to the parent view controller can solve a problem that the viewWillAppear of the child view controller will not cause.

+1
source share

All Articles