gpt4 book ai didi

c# - Delegate 在 iOS 12.0 中被弃用。请采用WKWebView。我如何在 Xamarin 中解决这个问题?

转载 作者:行者123 更新时间:2023-11-28 23:31:34 26 4
gpt4 key购买 nike

我正在尝试为 iOS 和 Android 创建自定义 WebView 渲染器。我的主要目标是使 WebView 适合它的 HTML 内容;

谷歌搜索后,我很快意识到这只有通过为 iOS 和 Android 制作自定义渲染器才有可能。

我正在使用需要委托(delegate)的解决方案。您可以查看解决方案here .但是,此解决方案是在 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?

最佳答案

实际上很简单,创建一个像这样的自定义 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)));
}
}
}
}

关于c# - Delegate 在 iOS 12.0 中被弃用。请采用WKWebView。我如何在 Xamarin 中解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56291291/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com