Search code examples
webviewxamarin.iosrotationxamarin.formscustom-renderer

How to fix rotation for WebView custom renderer for iOS using Xamarin.Forms?


I have created a custom renderer for a WebView in my Xamarin.Forms project. The WebView works great on Android. Unfortunately, on iOS, when the device is rotated, the webpage (any webpage) does not correctly adjust to the new dimensions of the WebView. If I use the built in WebView for Forms, the pages correctly resize on rotate.

What am I doing wrong with my custom renderer?

Below is a stripped down version of my custom renderer (the issue still occurs):

using Xamarin.Forms.Platform.iOS;
using Xamarin.Forms;
using UIKit;
using Foundation;

[assembly: ExportRenderer(typeof(WebView), typeof(MyProject.iOS.WebViewRenderer))]
namespace MyProject.iOS {
    public class WebViewRenderer : ViewRenderer<WebView, UIWebView> {
        protected override void OnElementChanged(ElementChangedEventArgs<WebView> e) {
            if (Control == null) {
                var webView = new UIWebView(Frame);
                webView.AutoresizingMask = UIViewAutoresizing.All;
                SetNativeControl(webView);
                webView.LoadRequest(new NSUrlRequest(new NSUrl("http://cnn.com")));
            }
        }
    }
}

Solution

  • To fix the issue, add the following to the custom renderer:

    public override SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint) {
        return new SizeRequest(Size.Zero, Size.Zero);
    }