我正在开发一个 Xamarin.Forms PCL 项目,该项目以 WebView 的形式显示帖子,因此我添加了可点击的内容,例如主题标签。
我遇到的问题是 WebView 无法适应其内容的大小。 WebView 不加载实际站点我使用以下方法将 HTML 绑定到 ListView 中的每个帖子
"<html><p>" + body + "</p></html>"
我尝试研究自定义渲染器并遵循本教程 http://lukealderton.com/blog/posts/2016/may/autocustom-height-on-xamarin-forms-webview-for-android-and-ios/并最终得到以下代码
对于Android我用过
#pragma warning disable CS0618 // Type or member is obsolete
public class CustomWebViewAndroid : WebViewRenderer
{
static CustomWebView _xwebView = null;
WebView _webView;
class ExtendedWebViewClient : Android.Webkit.WebViewClient
{
public override async void OnPageFinished (WebView view, string url)
{
if (_xwebView != null) {
int i = 10;
while (view.ContentHeight == 0 && i-- > 0) // wait here till content is rendered
await System.Threading.Tasks.Task.Delay (100);
_xwebView.HeightRequest = view.ContentHeight;
}
base.OnPageFinished (view, url);
}
}
protected override void OnElementChanged (ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged (e);
_xwebView = e.NewElement as CustomWebView;
_webView = Control;
if (e.OldElement == null) {
_webView.SetWebViewClient (new ExtendedWebViewClient ());
}
}
}
对于 iOS
public class CustomWebViewiOS : WebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
Delegate = new CustomWebViewDelegate(this);
}
}
public class CustomWebViewDelegate : UIWebViewDelegate
{
CustomWebViewiOS webViewRenderer;
public CustomWebViewDelegate(CustomWebViewiOS _webViewRenderer = null)
{
webViewRenderer = _webViewRenderer ?? new CustomWebViewiOS();
}
public override async void LoadingFinished(UIWebView webView)
{
var wv = webViewRenderer.Element as CustomWebView;
if (wv != null)
{
await System.Threading.Tasks.Task.Delay(100); // wait here till content is rendered
wv.HeightRequest = (double)webView.ScrollView.ContentSize.Height;
}
}
}
然后将其应用到 XAML 中,如下所示
<StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<local:CustomWebView HeightRequest="20" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<local:CustomWebView.Source>
<HtmlWebViewSource Html="{Binding HtmlContent}"/>
</local:CustomWebView.Source>
</local:CustomWebView>
</StackLayout>
在 Android 上,它会剪掉帖子正文的一半。
在 iOS 上,它不能正确地间隔帖子并截断其上方帖子的时间戳。我的猜测是 ViewCell 的高度会根据内容进行调整,但不会考虑其他帖子。同样对于 iOS,如果文本占两行,则需要您滚动才能查看其余内容。