如何阻止旋转以仅允许 xamarin 形式的纵向模式? [英] How can I block rotation to only allow portrait mode in xamarin forms?

查看:41
本文介绍了如何阻止旋转以仅允许 xamarin 形式的纵向模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在特定页面上阻止轮播,这必须同时适用于 Android 和 iOS.

I need to block rotation on a specific page and this has to work both for Android and iOS.

我尝试使用 NuGet Plugin.DeviceOrientation 并添加以下代码

I tried using NuGet Plugin.DeviceOrientation and adding the following code

protected override void OnAppearing()
        {
            base.OnAppearing();
            if (CrossDeviceOrientation.IsSupported) 
                CrossDeviceOrientation.Current.LockOrientation(Plugin.DeviceOrientation.Abstractions.DeviceOrientations.Portrait);
        }


protected override void OnDisappearing()
        {
            base.OnDisappearing();
            if (CrossDeviceOrientation.IsSupported) 
                CrossDeviceOrientation.Current.UnlockOrientation();
        }

但抛出异常:System.NullReferenceException: '未将对象引用设置为对象的实例.'

but throws exception: System.NullReferenceException: 'Object reference not set to an instance of an object.'

推荐答案

对于 Xamarin.Forms,你可以依赖服务.

For Xamarin.Forms, you could dependency service.

创建界面:

 public interface IRotate
{
    void ForcePortrait();
}

安卓:

[assembly: Xamarin.Forms.Dependency(typeof(RoateHandler))]
namespace RotatePage.Droid
{
class RoateHandler : IRotate
{
    public void ForcePortrait()
    {
        ((Activity)Forms.Context).RequestedOrientation = ScreenOrientation.Portrait;
    }
}
}

iOS:

[assembly: Xamarin.Forms.Dependency(typeof(RoateImplementation))]
namespace RotatePage.iOS
{
class RoateImplementation : IRotate
{
    public void ForcePortrait()
    {
        UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.Portrait), new NSString("orientation"));
    }
}
}

用法:

DependencyService.Get().ForcePortrait();

DependencyService.Get().ForcePortrait();

截图:

这篇关于如何阻止旋转以仅允许 xamarin 形式的纵向模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆