Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

programmatically create container view in ios

I know how to create a container view in iOS via storyboard but it won't let me have a container view in a collection view cell. I'd like one of the cells to load another controller as a container. How would I go about doing this?

like image 798
moger777 Avatar asked Dec 25 '22 21:12

moger777


1 Answers

Before I give you the code you must realize this is certainly a bad idea. UITableViewCells are highly reusable and are just raw views not backed by a a real view controller (just a data source). Container views are designed to be nested controllers and not just placed inside of a UIView (like a table cell). But I digress:

Here is the Apple docs related to container views (search for container view).

Under the section Adding and Removing a Child:

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

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

When configuring a cell it will most likely already have a container view inside of it (from its previous configuration). So before adding a new one on top of that you should first attempt to reuse what you have already added. But again, this solution is not really advisable, but you already should know that since IB blocked you from doing it.

like image 186
Firo Avatar answered Dec 28 '22 09:12

Firo