【发布时间】:2021-02-26 10:47:18
【问题描述】:
我在使用 Xamarin Forms 4.8.0.1364 和 ContentPage 的 iOS 应用程序中让 WebView 正确占据整个屏幕时遇到问题。本机控件是 WkWebView,正在 iPhone 12、iOS 14.1 模拟器中进行测试。
另外,当设备转回纵向时,WebView 的大小不对,或者 WebView 中的内容渲染不正确。
XAML 如下(注意相对于屏幕截图的 BackgroundColor):
<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModel="clr-namespace:MyCompany.MyApp.ViewModels;assembly=MyAssembly"
x:Class="MyCompany.MyApp.Views.MyWebViewPage"
BackgroundColor="Green" >
<ContentPage.BindingContext>
<viewModel:MyPageViewModel URL="https://login.somepage.com" />
</ContentPage.BindingContext>
<ContentPage.Content>
<Grid BackgroundColor="Blue">
<WebView x:Name="WebView"
BackgroundColor="Black"
Source="{Binding URL}"
Cookies="{Binding Cookies}">
</WebView>
</Grid>
</ContentPage.Content>
</ContentPage>
注意:我尝试了很多东西,并删除了所有没有影响的东西。已经在 HorizontalOptions 和 VerticalOptions 上尝试过 FillAndExpand,以及在 Grid 列/行上使用星形和自动调整大小。我删除了与 XAML 没有区别的所有内容。 结果是:
我想看到的是 WebView 占据了整个屏幕,而没有各种颜色可见(绿色、蓝色、黑色),并且在旋转之后,内容应该符合预期。
我也尝试过自定义渲染器。
public class MyWebViewRenderer : WkWebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
}
}
public override void LayoutSubviews()
{
Bounds = CalculateBounds();
base.LayoutSubviews();
}
private CGRect CalculateBounds()
{
var screenBounds = UIScreen.MainScreen.Bounds;
var statusBarHeight = UIApplication.SharedApplication.StatusBarFrame.Height;
nfloat navBarHeight = 0;
var uiNavController = Window?.RootViewController as UINavigationController;
if (uiNavController?.TopViewController != null)
{
navBarHeight = uiNavController.NavigationBar.Bounds.Height;
}
var adjustedHeight = statusBarHeight + navBarHeight;
var bounds = new CGRect(screenBounds.X, screenBounds.Y + adjustedHeight,
screenBounds.Width, screenBounds.Height - adjustedHeight);
return bounds;
}
}
MyWebViewRenderer.LayoutSubviews中计算bounds时的结果,结果为:
纵向模式下的初始页面加载: (我的身高计算是关闭的?)
旋转到横向后(实际上看起来还可以):
旋转回纵向后,高度计算正常,但不知何故发生了偏移:
有什么建议吗?
谢谢
【问题讨论】:
-
您还可以添加检查以查看它是哪个页面,然后保持该页面的方向固定
标签: ios xamarin.forms layout webview wkwebview