0

I have an storyboard with a ViewController and inside the ViewController I have a UICollectionView with a prototype cell.

I already have an "MyCollectionViewController" (because I try to wrap my CollectionViewController in a ViewController). Now I want to reuse that controller but I can't figure out how to connect the CollectionView from the storyboard with a new CollectionViewController. Assigning the CollectionView from the CollectionViewController to the Outlet in the ViewController doesn't seem to work.

I know I could make the cell prototype a .xib file and create the CollectionView in code. But my employer prefers having everything in the storyboard for easier maintenance.

EDIT: The answer from chkn works great. To connect the parent view controller to the container you can override the PrepareSegue method like this.

    public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
    {
        base.PrepareForSegue (segue, sender);
        if (segue.SourceViewController == this) {
            if (segue.DestinationViewController.GetType () == typeof(MyChildViewController)) {
                MyChildViewController childViewController = segue.DestinationViewController as MyChildViewController;
            }
        }
    }
Superwayne
  • 1,146
  • 1
  • 12
  • 22

1 Answers1

1

You can't assign a view from one view controller into an outlet on another view controller.

You can, however, have a single view controller containing the collection view, and then embed that view controller onto other view controllers using container views.

Simply create the view controller hosting the UICollectionView (it's easy to just use a UICollectionViewController, but it doesn't matter). Then on each view controller you want to embed it in, drag a Container View from the toolbox and remove the default view controller that comes with it. Then, Ctrl+drag from the Container View to the shared UICollectionView controller you want to embed.

Your storyboard might look something like this:

Screenshot

That example is available here:
https://github.com/chkn/StoryboardExamples/tree/master/CollectionViewReuse

chkn
  • 647
  • 7
  • 14
  • That looks like the right approach for my problem, thank you! I'll let you now if I can make it work. – Superwayne Mar 26 '15 at 10:02
  • It works perfectly and I can even reuse my previous CollectionViewController. – Superwayne Mar 26 '15 at 10:08
  • Just one thing I don't understand: How do I get the embedded controller? I need to pass an variable to the embedded view controller before I push the parent view controller to the navigation stack. – Superwayne Mar 26 '15 at 12:12
  • Thats what I did. Added the code in my question of others. – Superwayne Mar 27 '15 at 15:49