Search code examples
xamarinxamarin.iosuikitcore-graphics

How to use Core Graphics in a UIViewController's Subview in Xamarin iOS?


I have set up the following structure in my storyboard. I have a UIViewController that contains a UIView which contains buttons, text, and a smaller UIView. I would like to draw to the smaller UIView.

The current working code I have is:

public partial class MyDrawingController : UIViewController
{
    public MyDrawingController (IntPtr handle) : base(handle) { }

    public override void LoadView ()
    {
        base.LoadView ();
        View = new NewDrawingView ();
    }
}

public class NewDrawingView : UIView
{
    public NewDrawingView () : base() {}

    public override void Draw (CGRect rect)
    {
        base.Draw (rect);
        DrawMe (rect);
    }

    public void DrawMe(CGRect rect) {
        // Drawing code
    }
}

This results in the larger UIView's content being entirely replaced by my drawing (covering my text and buttons).

    NewDrawingView = new NewDrawingView();

While this calls the constructor, the UIView's Draw method is never called, thereby never giving be correct access to the UIGraphics context to do drawing.

Edit:

    View.AddSubview(new NewDrawingView());

Also calls the constructor and not the Draw method (and doesn't appear to display a new view). How can I call the draw method of subview or otherwise draw within a subview?


Solution

  • Found what I needed at long last at:

    How to add subview above the keyboard in monotouch/Xamarin.Ios?

    public override void LoadView ()
    {
        base.LoadView ();
        NewDrawingView drawingView = new NewDrawingView{
            Frame = new RectangleF (0, 0, 100, 100)
        };
        View.AddSubview (drawingView);
    }
    

    This code correctly initializes my drawing view and calls the draw method when adding the subview to the view controller's main view.