Xamarin.Forms - iOS上的响应式WebViews存在奇怪的高度问题。

问题描述 投票:0回答:1

我有一个ListView,我想在里面绑定多个高度不同的webviews。我想根据每个webview的内容计算它的高度,并相应地显示。

在Android上可以工作--在iOS上,所有的WebViews都太大了。

       await System.Threading.Tasks.Task.Delay(100);
       var result = (double)webView.ScrollView.ContentSize.Height;
       _webView.HeightRequest = result;

奇怪的是:webview的html字符越多,它就越大。因此,我可以只添加一个字符,而另外50px的高度将被添加。

这里有很多代码,但这里是github上项目的链接。https:/github.comSlimboTimboMultipleWebViews。

xamarin.forms wkwebview
1个回答
1
投票

检查项目后,已经找到了原因,为什么不工作在iOS设备。

理由 是说 widthwebView.ScrollView.ContentSize 是不正确的,是太小了,是27。因此,它不能正确显示。

System.Console.WriteLine("----" + resultWidth + "-----"+ resultHeight + "----"+ _webView.Width);

輸出 :

2020-06-04 11:19:58.066542+0800 MultipleWebViews.iOS[50674:1690400] ----27-----642----375

解决办法 :

你可以计算一下 height 宽于 HybridWebView,并将计算后的 height 对于 HybridWebView .

DidFinishNavigation 方法代码如下。

public override async void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{

    try
    {
        var _webView = webViewRenderer.Element as HybridWebView;
        if (_webView != null)
        {
            await System.Threading.Tasks.Task.Delay(100);
            var resultWidth = (double)webView.ScrollView.ContentSize.Width;
            var resultHeight = (double)webView.ScrollView.ContentSize.Height;
            System.Console.WriteLine("----" + resultWidth + "-----"+ resultHeight + "----"+ _webView.Width);

            double result = MeasureTextHeightSize(_webView.messageContent, _webView.Width, UIFont.LabelFontSize, null);

            _webView.HeightRequest = result;

            MessagingCenter.Send<Object, PassModel>(this, "LoadFinished", new PassModel(_webView.Id, Convert.ToDouble(result)));
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error at HybridWebViewRenderer LoadingFinished: " + ex.Message);
    }
}

MeasureTextHeightSize ( 计算高度的方法 )

private double MeasureTextHeightSize(string text, double width, double fontSize, string fontName = null)
{
    var nsText = new NSString(text);
    var boundSize = new SizeF((float)width, float.MaxValue);
    var options = NSStringDrawingOptions.UsesFontLeading | NSStringDrawingOptions.UsesLineFragmentOrigin;

    if (fontName == null)
    {
        fontName = "HelveticaNeue";
    }

    var attributes = new UIStringAttributes
    {
        Font = UIFont.FromName(fontName, (float)fontSize)
    };

    var sizeF = nsText.GetBoundingRect(boundSize, options, attributes, null).Size;

    //return new Xamarin.Forms.Size((double)sizeF.Width, (double)sizeF.Height);
    return (double)sizeF.Height;
}

效果 :

enter image description here

说明: : 您可以修改 fontSize 并可以根据你当前系统的字体大小自定义该方法的返回值。并且还可以自定义返回值,如 return (double)sizeF.Height + 10 以适应屏幕。

© www.soinside.com 2019 - 2024. All rights reserved.