Anthony Shintoluggenprog Anthony Shintoluggenprog - 1 month ago 21
Objective-C Question

How to share UIView between transitioning UIViewController's (with addChildUsingController:)

Let's say that on the tap of a

the following happens before transitioning to

- (IBAction)levelSelectButton:(id)sender {
ViewControllerB* obj = [[ViewControllerB alloc] init];
[self addChildViewController:obj];
CGSize screenSize = [MainScreen screen];
CGFloat screenWidth = screenSize.width;
CGFloat screenHeight = screenSize.height;
obj.view.frame = CGRectMake(0,0,screenWidth,screenHeight);
[obj.view addSubview:_banner];

//[obj didMoveToParentViewController:self];
[self runPushAnimationWithController:obj];

shows up, I can see my
object) view in place, but when I return to
it is no longer there.

I have never used
methods before so I don't know if this is expected, but I want to be able to return to
still visible.

Do I need to retain it?


A view can only belong to a single superview. To quote Apple's docs:

Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.

So when you add your view to a newly created parent view controller, it gets removed from the current view controller's view hierarchy.

I would advise against doing this sort of thing. Just create a copy of the view in both places. If it uses large amounts of data, share the data (model) between view controllers, but not the view objects.

If you are completely set on moving your view around between view controllers, I would add a property to the new view controller and set that property rather than manipulating the other view controller's view hierarchy. You'll also have to pass the view BACK when you return to your current view controller.

You should treat a view controller's view hierarchy as private. Not doing that violates the principle of encapsulation.