MonoTouch Instantiating a ViewController programma

2019-08-15 09:53发布

问题:

I am trying to work with a container view in MonoTouch and I am following some tutorials online. They talk about adding and removing view controller programmatically from the container. I created a viewcontroller and view in the storyboard of my project and attached a few outlets and one action (for labels and buttons respectively). I created an overloaded construc

Here is the code in the view controller that I am trying to add viewControllers into the container view.

public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();
        ContainerView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight;
        _controllerOne = new IngredientsController("Perishables");
        _controllerTwo = new IngredientsController("Spices");
        AddChildViewController(_controllerOne);
        ContainerView.AddSubview(_controllerOne.View);
        _controllerOne.DidMoveToParentViewController(this)
    }

When I add the subview for _controllerOne I get an error because the elements on my controller are marked null. Is MonoTouch incapable of having view controllers being programmatically created if the controller was made in Interface Builder? Below are the two constructors for the Ingredient Controller. When the segue is used then all of the UI controls are initialized properly. Do I need to create the controller programmatically and then instantiate it that way? Any help would be appreciated.

//This ctor does not work
public IngredientsController (string title) : base(NSObjectFlag.Empty)
{
_ingredientTitle = title;
}

//This ctor works
public IngredientsController (IntPtr handle) : base (handle)
{
}

回答1:

Try to swap the AddSubView() and DidMoveToParentViewController() methods like below:

public override void ViewDidLoad ()
{
    base.ViewDidLoad ();
    ContainerView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight;
    _controllerOne = new IngredientsController("Perishables");
    _controllerTwo = new IngredientsController("Spices");
    this.AddChildViewController(_controllerOne);        // Root child controller.
    _controllerOne.DidMoveToParentViewController(this); // Confirm the rooting.
    ContainerView.AddSubview(_controllerOne.View);      // Access the view.
}


回答2:

Try instantiating the view controller like this:

public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();

        this.ContainerView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight;

        var newController = this.Storyboard.InstantiateViewController("IngredientsController");

        this.AddChildViewController (newController);        
        this.ContainerView.AddSubview (mapController.View);
    }

Make sure you set the Storyboard Id in the properties panel for the ViewController