本文介绍了让 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")); 
     }
   }
}

这篇关于让 xamarin 表单中的一个共享页面保持横向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 18:01