让 xamarin 表单中的一个共享页面保持横向

问题描述:

我必须让 xamarin 表单应用程序中的页面进入横向模式并保持横向模式.它是共享项目,在 android 和 iOS 中使用.有人知道实现这一目标的方法吗?

I have to make a page in a xamarin forms app go to landscape mode and stay in landscape mode. It is the shared project and used in android and iOS. Would anyone know of a way to achieve this?

Supun 的答案 是正确的,但它强制使用纵向模式.如果你想强制横向,这是你的方式:

Supun's answer is on the right track, but it forces portrait mode. If you want to force landscape, this is your way to go:

ThirdPage.xaml.cs:

public new void OnAppearing()
{
    base.OnAppearing();
    MessagingCenter.Send(this, "PreventPortrait");
}

public new void OnDisappearing()
{
    base.OnDisappearing();
    MessagingCenter.Send(this, "AllowPortrait");
}

安卓:

在 MainActivity 的 OnCreate() 中:


Android:

In OnCreate() in MainActivity:

MessagingCenter.Subscribe<ThirdPage>(this, "PreventPortrait", sender =>
{
    RequestedOrientation = ScreenOrientation.Landscape;
});

MessagingCenter.Subscribe<ThirdPage>(this, "AllowPortrait", sender =>
{
    RequestedOrientation = ScreenOrientation.Unspecified;
});

iOS:

AppDelegate.cs:

public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations(UIApplication application,UIWindow forWindow)
{ 
   var mainPage = Xamarin.Forms.Application.Current.MainPage;
   if (mainPage.Navigation.NavigationStack.Last() is ThirdPage)
    {
    return UIInterfaceOrientationMask.AllButUpsideDown;
    }
  return UIInterfaceOrientationMask.Landscape;
}

ThirdPageRenderer.cs:在页面消失时将配置设置回纵向:

[assembly: ExportRenderer(typeof(ThirdPage), typeof(ThirdPageRenderer))]
namespace MyForm.iOS
{
  public class ThirdPageRenderer : PageRenderer
  { 
    public override void ViewWillDisappear(bool animated)
     {
     base.ViewWillDisappear(animated);
     UIDevice.CurrentDevice.SetValueForKey(NSNumber.FromNInt((int)(UIInterfaceOrientation.Landscape)), new NSString("orientation")); 
     }
   }
}