检查项目后,发现不能在iOS设备上运行的原因。
原因是webView.ScrollView.ContentSize的width不正确,太小就是27。因此,它无法正确显示。
System.Console.WriteLine("----" + resultWidth + "-----"+ resultHeight + "----"+ _webView.Width);
输出:
2020-06-04 11:19:58.066542+0800 MultipleWebViews.iOS[50674:1690400] ----27-----642----375
解决方案:
您可以通过HybridWebView的宽度计算height,并将计算后的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;
}
效果:
注意:您可以根据您当前的系统字体大小修改此方法的fontSize。也可以自定义返回值,如return (double)sizeF.Height + 10以适应屏幕。