Creating a Native View from a Xamarin.Forms View

WARNING: this is a expert level technique and isn’t officially supported by Xamarin.

Personally I feel like this is the holy grail of Xamarin.Forms development, having the ability to jump between both Xamarin.Forms Views and Native Views. I’ve used this technique multiple times in Xamarin.Forms apps.

It’s primarily used when you’ve created a custom renderer and you’re working against Native UI APIs, this could be in the native maps API or a 3rd party native component. Now once you’re in the Native area of the application there’s cases where you need to show a view for the user but you still want to have the View shared between the platforms.

To give you an idea the structure might be as follows.

Xamarin.Forms -> Native View

In the diagram above the secret sauce is in orange, taking a Xamarin.Form View and converting that into a native view. This converts to a UIView in iOS and ViewGroup in Android.

Below I’ve written two helper classes that take a Xamarin.Forms view and convert it into the NativeViews. In my experience this code works the best when the Xamarin.Forms view is a Layout.

iOS Converter Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class FormsViewToNativeiOS
{
    public static UIView ConvertFormsToNative(Xamarin.Forms.View view, CGRect size)
    {
        var renderer = RendererFactory.GetRenderer (view);
 
        renderer.NativeView.Frame = size;
 
        renderer.NativeView.AutoresizingMask = UIViewAutoresizing.All;
        renderer.NativeView.ContentMode = UIViewContentMode.ScaleToFill;
 
        renderer.Element.Layout (size.ToRectangle());
 
        var nativeView = renderer.NativeView;
 
        nativeView.SetNeedsLayout ();
 
        return nativeView;
    }
}

Android converter class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class FormsToNativeDroid
{
    public static ViewGroup ConvertFormsToNative(Xamarin.Forms.View view, Rectangle size)
    {
        var vRenderer = RendererFactory.GetRenderer (view);
        var viewGroup = vRenderer.ViewGroup;
        vRenderer.Tracker.UpdateLayout ();
        var layoutParams = new ViewGroup.LayoutParams ((int)size.Width, (int)size.Height);
        viewGroup.LayoutParameters = layoutParams;
        view.Layout (size);
        viewGroup.Layout (0, 0, (int)view.WidthRequest, (int)view.HeightRequest);
        return viewGroup; 
    }
}

I’ve created a github sample application, please find it https://github.com/rid00z/LoadingFormsViewFromNative. *** Please note this iOS project uses UIPopover which is only available on iPad so you must use the iPad for this demo.

If you want to know more awesome Xamarin.Forms techniques then my eCourse is a must do! ‘Secrets of a Xamarin.Forms Ninja

Thanks

Michael

 

1 Response

Leave a Reply