如何在xamarin.forms中旋转页面

如何在xamarin.forms中旋转页面,xamarin.forms,Xamarin.forms,应用程序中有一些页面,有些页面是纵向的,但有些页面是横向的。 如果使用android本机代码,我可以这样做: <activity android:name=".activity1" android:screenOrientation="landscape" /> <activity android:name=".activity2" android:screenOrientation="portra

应用程序中有一些页面,有些页面是纵向的,但有些页面是横向的。 如果使用android本机代码,我可以这样做:

    <activity
        android:name=".activity1"
        android:screenOrientation="landscape" />
    <activity
        android:name=".activity2"
        android:screenOrientation="portrait"/>


但是如何在xamarin.forms中定义不同的屏幕方向

您可以通过创建依赖项来实现这一点

在主窗体项目中创建一个界面:

namespace Example
{
    public interface IOrientationHandler
    {
        void ForceLandscape();
        void ForcePortrait();
    }
}
像这样称呼它:

DependencyService.Get<IOrientationHandler>().ForceLandscape();
DependencyService.Get<IOrientationHandler>().ForcePortrait();
iOS

[assembly: Xamarin.Forms.Dependency(typeof(OrientationHandlerImplementation))]
namespace Example
{
    public class OrientationHandlerImplementation : IOrientationHandler
    {
        public void ForceLandscape()
        {
            UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.LandscapeLeft), new NSString("orientation"));
        }

        public void ForcePortrait()
        {
            UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.Portrait), new NSString("orientation"));
        }
    }
}

签出此项:您这样做是对的:)非常感谢。以后有什么办法撤销此项吗?像将其返回到基于实际设备方向设置方向一样?在Appearing方法中,您可以使用此DependencyService.Get().force横向();OnDisappearing方法使用此DependencyService.Get().ForcePatrait();
[assembly: Xamarin.Forms.Dependency(typeof(OrientationHandlerImplementation))]
namespace Example
{
    public class OrientationHandlerImplementation : IOrientationHandler
    {
        public void ForceLandscape()
        {
            UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.LandscapeLeft), new NSString("orientation"));
        }

        public void ForcePortrait()
        {
            UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.Portrait), new NSString("orientation"));
        }
    }
}