0

我在 Xamarin.Forms 项目中为 WebView 创建了一个自定义渲染器。WebView 在 Android 上运行良好。不幸的是,在 iOS 上,当设备旋转时,网页(任何网页)都无法正确调整到 WebView 的新尺寸。如果我使用内置的 WebView for Forms,页面会在旋转时正确调整大小。

我的自定义渲染器做错了什么?

下面是我的自定义渲染器的精简版本(问题仍然存在):

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")));
            }
        }
    }
}
4

2 回答 2

2

要解决此问题,请将以下内容添加到自定义渲染器:

public override SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint) {
    return new SizeRequest(Size.Zero, Size.Zero);
}
于 2016-08-29T18:29:31.813 回答
0

要解决旋转问题,您需要在创建 UIWebView 时使用 NativeView.Bounds。

[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespaceMobile.App.iOS
{
    public class CustomWebViewRenderer : ViewRenderer<CustomWebView, UIWebView>
    {      
        protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                var webView = new UIWebView(NativeView.Bounds);

                webView.ShouldStartLoad += HandleShouldStartLoad;
                webView.AutoresizingMask = UIViewAutoresizing.All;
                webView.ScalesPageToFit = true;                
                SetNativeControl(webView);

                webView.LoadRequest(new NSUrlRequest(new NSUrl(Element.Url)));
            }
        }

        public override SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
        {
            return new SizeRequest(Size.Zero, Size.Zero);
        }
    }
}
于 2016-09-27T18:57:22.097 回答