Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper way to add a view controller to the view hierarchy?

I have a view controller (A) that loads a view controller (B) and uses it's view in my view hierarchy. If I add B's view to A's view hierarchy, and I don't manually forward events like viewWillAppear, I can't handle them in the B controller. (From the viewWillAppear: docs)

Warning: If the view belonging to a view controller is added to a view hierarchy directly, the view controller will not receive this message. If you insert or add a view to the view hierarchy, and it has a view controller, you should send the associated view controller this message directly. Failing to send the view controller this message will prevent any associated animation from being displayed.

What's the correct way to nest view controllers? (Like NavBarController does it.) If it's just a question of needing to forward a group of events to the nested controller, what are all of the events that I need to forward?

like image 744
Douglas Mayle Avatar asked Oct 03 '09 15:10

Douglas Mayle


1 Answers

There is no magic solution here. The correct solution is to manually send these messages.

The viewWillAppear:/viewDidAppear: and viewWillDisappear:/viewDidDisappear: messages are the only messages you need to manually send to the child view controller.

You should implement all four of these methods in the parent view controller and send the same message to the child view controller whenever the parent receives the message and the child is loaded.

In addition, when you add the child view controller's view, you should send the viewWillAppear:/viewDidAppear: messages if the parent's view.window is non-nil. When you remove the view, you should send the viewWillDisappear:/viewDidDisappear: messages if the parent's view.window is non-nil.

like image 126
Matt Gallagher Avatar answered Oct 04 '22 22:10

Matt Gallagher