Container views in IOS

ios

Solution

If I follow your question, you're asking how to use view controller containment in code. I'd suggest checking out Creating Custom Container View Controllers section of the View Controller Programming Guide, which shows you code for doing this, including adding a child view controller:

[self addChildViewController:content];                 // 1
content.view.frame = [self frameForContentController]; // 2
[self.view addSubview:self.currentClientView];
[content didMoveToParentViewController:self];          // 3

When using child view controllers (at least ones that don't take up the whole screen), it's useful to have a `UIView` on the parent view controller's view, that dictates the boundaries of the child view controller. It greatly simplifies a bunch of tasks. In the above code snippet, they're assuming that the subview is called `frameForContentController`.

Or removing one (in this code snippet, `content` is the `UIViewController *` that references the child controller being removed):

[content willMoveToParentViewController:nil];  // 1
[content.view removeFromSuperview];            // 2
[content removeFromParentViewController];      // 3

And if you want to replace a child controller with another child controller:

- (void) cycleFromViewController: (UIViewController*) oldC
                toViewController: (UIViewController*) newC
{
    [oldC willMoveToParentViewController:nil];                        // 1
    [self addChildViewController:newC];

    newC.view.frame = [self newViewStartFrame];                       // 2
    CGRect endFrame = [self oldViewEndFrame];

    [self transitionFromViewController: oldC toViewController: newC   // 3
          duration: 0.25 options:0
          animations:^{
             newC.view.frame = oldC.view.frame;                       // 4
             oldC.view.frame = endFrame;
           }
           completion:^(BOOL finished) {
             [oldC removeFromParentViewController];                   // 5
             [newC didMoveToParentViewController:self];
            }];
}

I'd also suggest checking out WWDC 2011 - Implementing UIViewController Containment.

Problem

I wanted to use a Container View to initiate another view controller, but I can't see to find any information on how to alloc it programmly. I can do it from the user interface, but if I want to create one with the coes, and link it up to a UIviewController, how can I do that? Does it behave like a normal UIview?

Original source