简体   繁体   中英

Xamarin iOS: How to connect a view from a storyboard to a controller?

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;
            }
        }
    }

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:

截图

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM