问题
I am building a UIViewController
with a XIB. In this XIB, I have placeholders (UIView
objects in the XIB) in which I place other views, from other view controllers. (By the way, I could also add these views directly, without placeholders)
I am not buiding a container view controller: I mean it's not a UINavigationController
. It's a just a "usual" view controller. Imagine for example that I have a small subview in my view for a "Facebook" logo and a counter. This "facebook view" is attached to another view controller that is called when the "Facebook view" is touched. So, the "Facebook controller" definitely needs to be a @property
of my "main" view controller.
In this situation, should I really use addChildViewController:
and all the mechanism? Or no?
Thanks!
回答1:
You should not be using a UIViewController merely to "fish" into a .xib file for you to obtain the view. If that's all you want it for, don't do that. Just load the nib and pull out the view, directly:
NSArray* objects = [[UINib nibWithNibName: @"MyNib" bundle: nil]
instantiateWithOwner:nil options:nil];
UIView* v = (UIView*)[objects firstObject];
But if you are using a UIViewController in conjunction with this .xib file for some other reason, e.g. to keep it alive so that a button inside the .xib can send messages to this UIViewController, then absolutely you must make a proper parent-child relationship, as I describe in my book: http://www.apeth.com/iOSBook/ch19.html#_container_view_controllers
回答2:
Yes, you should. By doing so, the containing view controller sends proper view controller lifecycle events to the child view controllers.
You say you aren't building a container view controller but you are. Adding the view of another view controller to another view controller is the definition of a container view controller.
See the "Implementing a Container View Controller" section of the docs for UIViewController
on the proper sequence of method calls you should make. It's more than just calling addChildViewController
.
回答3:
You can instantiate your insider ViewController, and just add its view (myInsiderViewController.view) to your main viewController:
[mainViewController.view addSubView:myInsiderViewController.view];
来源:https://stackoverflow.com/questions/29973948/shall-i-really-use-addchildviewcontroller-when-i-add-a-view-to-another-view-and