iOS - Can't Add PlotView via AddSubview

Oystein Bjorke 10 years ago 0
This discussion was imported from CodePlex

benhysell wrote at 2014-03-12 23:55:

I'm curious why this doesn't work...

Say I'm in a class that is a UIViewController, I would expect I could do the following:
var plot = new PlotView ();
plot.Model = graph.Plot;
plot.BackgroundColor = UIColor.Red;
this.View.AddSubview(plot);
This will not show the plot, however if I do
this.View = plot
The plot shows up fine.

I would have expected I could call AddSubView(plot) and it would have worked.

Where I'm running into problems is I have a UIViewController that I'm adding to another UIViewController using AddChildViewController...and my plot won't render.

Thoughts?

objo wrote at 2014-03-13 07:04:

Sorry, I don´t know the answer. I would like to know too!

The control was refactored using the example in
http://docs.xamarin.com/guides/ios/user_interface/designer/ios_designable_controls_walkthrough/
with the goal to also make it usable from the Xamarin Studio designer.

benhysell wrote at 2014-03-13 14:12:

I'll see if I can take a look and figure out what is going on, can you create an issue in the issue tracker to track this?

benhysell wrote at 2014-03-14 01:12:

I think I found the answer...I do not believe this is a bug, but feedback is welcome.

Take the code in the ExampleBrowser for iOS
private void GraphView(ExampleInfo exampleInfo)
{
    var dvc = new GraphViewController (exampleInfo);
    navigation.PushViewController (dvc, true);
}
What I was attempting to do in my app was to take a UIViewController and add it to a second UIViewController, an allowed operation I believe, by doing the following
private void GraphView(ExampleInfo exampleInfo)
{
    var dvc = new GraphViewController (exampleInfo);
    var newGraphViewController = new UIViewController ();   
    newGraphViewController.AddChildViewController (dvc);
    newGraphViewController.View.AddSubview (dvc.View);
    navigation.PushViewController (newGraphViewController, true);
}
The above produced an empty view, nothing to show on the screen. The reason is, when dvc calls LoadView() the View.Frame of dvc is 0,0,0,0, the frame has no position and no size.

To properly get this to work one needs to manually set the View.Frame of the child UIViewController. The following code works fine:
private void GraphView(ExampleInfo exampleInfo)
{
    var dvc = new GraphViewController (exampleInfo);
    var newGraphViewController = new UIViewController ();
    dvc.View.Frame = newGraphViewController.View.Frame;
    newGraphViewController.AddChildViewController (dvc);
    newGraphViewController.View.AddSubview (dvc.View);
    navigation.PushViewController (newGraphViewController, true);
}
Not a bug, I believe this is as designed by iOS.