Is it advisable to add a UIViewController
's view
to another UIViewController
's view
?
Please explain why it is a good practice or a bad practice.
Apple and thus most people following Apple's guidelines will tell you it's bad practice and that Apple added ViewController containment (childViewControllers) for that reason. Unfortunately, most people blindly follow that and won't tell you why it is bad practice. And I'm glad that you do ask that.
The truth is, in a model-view-controller architecture, views should be reuseable regardless of the content they contain, thus the view and the object controlling the view's content should not be the same. Which is exactly what a UIViewController does yet prior to iOS5 Apple discouraged you to use them in multiples while it's a very logical thing to do. Ofcourse this was confusing, many people ignored the guidelines and did it anyway, myself included, apps worked fine and passed app store validation which caused even more confusion. The result is that to this day people still ask questions about this even more than a year after Apple caved and gave us custom container ViewControllers. I've seen people respond to this question often with complex answers as far as recreating UIViewController as a class that inherits from NSObject for very simple issues. Just because Apple discourages using UIViewControllers and without even knowing why.
Since adding a ViewController's view as a subview will often work perfectly and ViewController containment is not available in iOS4 which many still support, too many people don't bother using ViewController containment. It is the cleaner solution and when you feel like using ViewControllers in ViewControllers, you should use it when possible. If not, in most situations you should be able to simply add a ViewController's view as a subview, you just have to know in which situations.
Here's what you can expect if you just add a ViewController's view to another view:
I definitely wouldn't encourage it but I don't discourage it either. It's situational and if you don't have to support iOS4 anymore then you can mostly avoid it. But if you keep the above list in mind then it won't cause any harm either and your app will work fine.
Sometimes it's ok, and sometimes it's not. It's hard to give a better answer than that without showing some diagrams and explaining the relationship between the view controller hierarchy and the view hierarchy.
Fortunately, Apple has already done that. Watch the “Implementing UIViewController Containment” video from WWDC 2011 for a detailed explanation of when it's ok and when it's not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With