Xamarin Forms - Webview 未显示

Xamarin Forms - Webview not showing up

我正在开发一个小型 Xamarin.Forms webview 应用程序。这是之前回答的问题的后续问题,

所以我实现了一个工具栏和一个后退按钮并且可以正常工作。但是当我 运行 带有模拟器的程序已经打开时(我正在使用 Genymotion),程序 运行s 并显示工具栏和后退按钮...但是不会显示 webview。

但奇怪的是,有时当我 运行 当模拟器处于睡眠模式时程序然后将其切换回程序时,程序运行完美。另外,当我在 iOS 上测试它时,它只显示工具栏,根本没有 webview!通常情况下,模拟器不会显示 webView。我也在我的 Android 设备上测试了这个,同样的事情发生了,它会显示工具栏而不是 webview。

我知道这有点令人困惑,但谁能帮我解决这个问题。

我将在下面附上我的代码:

App.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Xamarin.Forms;

namespace WebView_form
{
    public class App : Application
    {
        public App()
        {
            //const string URL = "http://www.google.com";
            MainPage = new NavigationPage(new WebPage());
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}

WebPage.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;

using Xamarin.Forms;

namespace WebView_form
{
    public class WebPage : ContentPage
    {
        private WebView webView;

        public WebPage()
        {
            webView = new WebView 
            {
                Source = "https://www.google.com"
            };


            // toolbar
            ToolbarItems.Add(new ToolbarItem("Back", null, () =>
                {
                    webView.GoBack();
                }));

            Content = new StackLayout
            {
                Children = { webView }
            };
        }
    }
}

如果有人能帮助我,那就太好了。

VerticalOptions 设置为 FillAndExpand,如果不起作用,对 HorizontalOptions 执行相同的操作。

可能 WebView 的尺寸高度为零,因为布局发生时视图仍然是空的。

所以像这样更改 WebPage.cs 中的代码;

// ... Other code

public WebPage()
{
  webView = new WebView 
  {
     Source = "https://www.google.com",
     VerticalOptions = LayoutOptions.FillAndExpand,
     HorizontalOptions = LayoutOptions.FillAndExpand
  };


  // toolbar
  ToolbarItems.Add(new ToolbarItem("Back", null, () =>
  {
     webView.GoBack();
  }));

  Content = new StackLayout
  {
     Children = { webView }
  };
}

// ... Other code

另一件需要考虑的事情:如果您正在响应 WebView.Navigating 事件,并且加载的页面是 WevView.Source,请确保不要将其 args.Cancel 设置为 true。 WebView.Navigating 的 iOS 实现会在加载 WebView.Source 时触发,但 Android 实现不会。如果当有问题的页面是 WebView.Source 时将 args.Cancel 设置为 true,WebView 将为空白。

将此设置到您的 Info.plist 中以绕过应用程序传输安全检查。访问 https://developer.apple.com/documentation/bundleresources/information_property_list/nsapptransportsecurity 了解更多信息。

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>

注意:我的 URL 已经是 HTTPS,不知道为什么它仍然被阻止。