Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an UIViewController's view as subview

Note to googlers, this Q-A is now six years out of date!

As Micky below and others mention, this is now done on an everyday basis with Containers in iOS.


I have a ViewController which controls many subviews. When I click one of the buttons I initialize another viewcontroller and show it's view as the subview of this view. However the subview exceeds the bounds of the frame for subview and infact fills the entire screen.

What could be wrong? I presume the problem is that UIViewController's view has a frame (0,0,320,460) and hence fills the entire screen (though it receive's touch events only when touched within the subview frame bounds). How can I resize the frame to fit as subview.

In short, I need help adding a viewcontroller's view as a subview to another viewcontroller's view.

Thanks!

like image 246
sperumal Avatar asked Sep 28 '09 12:09

sperumal


People also ask

How can you add subviews to your UIViewController's main view?

(i) Drag a container view in to your scene. Look at the UIViewController on the storyboard which Xcode gives you by default. (ii) Drag a new UICollectionViewController to anywhere on the main white area of the storyboard. (iii) Click the container view inside your scene.


1 Answers

As of iOS 5, Apple now allows you to make custom containers for the purpose of adding a UIViewController to another UIViewController particularly via methods such as addChildViewController so it is indeed possible to nest UIViewControllers

EDIT: Including in-place summary so as to avoid link breakage

I quote:

iOS provides many standard containers to help you organize your apps. However, sometimes you need to create a custom workflow that doesn’t match that provided by any of the system containers. Perhaps in your vision, your app needs a specific organization of child view controllers with specialized navigation gestures or animation transitions between them. To do that, you implement a custom container - Tell me more...

...and:

When you design a container, you create explicit parent-child relationships between your container, the parent, and other view controllers, its children - Tell me more

Sample (courtesy of Apple docs) Adding another view controller’s view to the container’s view hierarchy

- (void) displayContentController: (UIViewController*) content {    [self addChildViewController:content];                     content.view.frame = [self frameForContentController];     [self.view addSubview:self.currentClientView];    [content didMoveToParentViewController:self];           } 
like image 175
MickyD Avatar answered Sep 26 '22 02:09

MickyD