如何阻止旋转以仅允许 xamarin 表单中的纵向模式?
How can I block rotation to only allow portrait mode in xamarin forms?
我需要在 特定页面 上阻止旋转,这对 Android 和 iOS 都有效。
我尝试使用 NuGet Plugin.DeviceOrientation 并添加以下代码
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: 'Object reference not set to an instance of an object.'
对于Xamarin.Forms,您可以依赖服务。
创建接口:
public interface IRotate
{
void ForcePortrait();
}
Android:
[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();
截图:
我需要在 特定页面 上阻止旋转,这对 Android 和 iOS 都有效。
我尝试使用 NuGet Plugin.DeviceOrientation 并添加以下代码
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: 'Object reference not set to an instance of an object.'
对于Xamarin.Forms,您可以依赖服务。
创建接口:
public interface IRotate
{
void ForcePortrait();
}
Android:
[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();
截图: