委托在iOS 12.0中被弃用,请采用WKWebView,如何在Xamarin中解决这个问题?

mzillmmw  于 2023-08-01  发布在  iOS
关注(0)|答案(1)|浏览(69)

我正在尝试为iOS和Android创建自定义WebView渲染器。我的主要目标是使WebView适合它的HTML内容;
在谷歌搜索之后,我很快意识到这只有通过为iOS和Android定制渲染器才有可能。
我正在使用需要委托的解决方案。您可以在这里查看解决方案。然而,这个解决方案是在2016年发布的,因此我得到了这个编译时错误消息:“Delegate”在iOS 12.0中被弃用。不再支持;请采用“WKWebView”。

PostWebView.xaml

<WebView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Yoors.Views.Templates.PostWebView" x:Name="WebViewer" BackgroundColor="White" Margin="0, 10, 0, 0" VerticalOptions="FillAndExpand" HeightRequest="1000">
    <WebView.Source>
        <HtmlWebViewSource Html="{Binding Data.Content}" />
    </WebView.Source>
</WebView>

字符串

CustomWebViewRenderer.cs

public class CustomWebViewRenderer : WebViewRenderer
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);
            Delegate = new CustomUIWebViewDelegate(this);
        }

    }

CustomUIWebViewDelegate.cs

public class CustomUIWebViewDelegate : UIWebViewDelegate
    {

        CustomWebViewRenderer _webViewRenderer;

        public CustomUIWebViewDelegate(CustomWebViewRenderer webViewRenderer = null)
        {
            _webViewRenderer = _webViewRenderer ?? new CustomWebViewRenderer();
        }

        public override async void LoadingFinished(UIWebView webView)
        {
            var wv = _webViewRenderer.Element as PostWebView;
            if (wv != null)
            {
                await System.Threading.Tasks.Task.Delay(100); // wait here till content is rendered
                wv.HeightRequest = (double)webView.ScrollView.ContentSize.Height;
            }
        }
    }


如何根据我的代码采用WKWebView?

u91tlkcl

u91tlkcl1#

其实很简单。创建一个自定义Webview,类似于以下内容:

public class MyWebView : WebView
{
  public static readonly BindableProperty UrlProperty = BindableProperty.Create(
    propertyName: "Url",
    returnType: typeof(string),
    declaringType: typeof(MyWebView),
    defaultValue: default(string));

 public string Url
 {
    get { return (string)GetValue(UrlProperty); }
    set { SetValue(UrlProperty, value); }
 }
}

字符串
然后在iOS CustomRenderer中执行以下操作:

[assembly: ExportRenderer(typeof(MyWebView), typeof(MyWebViewRenderer))]
namespace WKWebView.iOS
{
public class MyWebViewRenderer : ViewRenderer<MyWebView, WKWebView>
{
    WKWebView _wkWebView;
    protected override void OnElementChanged(ElementChangedEventArgs<MyWebView> e)
    {
        base.OnElementChanged(e);

        if (Control == null)
        {
            var config = new WKWebViewConfiguration();
            _wkWebView = new WKWebView(Frame, config);
            SetNativeControl(_wkWebView);
        }
        if (e.NewElement != null)
        {
            Control.LoadRequest(new NSUrlRequest(new NSUrl(Element.Url)));
        }
    }
}
}

相关问题