方向锁定在 xamarin 中不起作用 ios

Orientation lock is not working in xamarin ios

我必须将单张 viewcontroller 锁定为横屏,而其他 viewcontroller 则全部旋转。我试过下面的代码。但是视图方向不会像风景一样改变。请提出您的建议。

AppDelegate.cs

public bool RestrictRotation
{
   get;
   set;
}

[Export("application:supportedInterfaceOrientationsForWindow:")]
public UIInterfaceOrientationMask GetSupportedInterfaceOrientations(UIApplication application, IntPtr
    forWindow)
{
    if (this.RestrictRotation)
        return UIInterfaceOrientationMask.Landscape;
    else
        return UIInterfaceOrientationMask.All;
}

Viewcontroller.cs

public override void ViewDidLoad()
{
    base.ViewDidLoad();
    this.RestrictRotation(true);
    // Perform any additional setup after loading the view, typically from a nib.
}

public override bool ShouldAutorotate()
{
    return false;
}

public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()
{
    return UIInterfaceOrientationMask.Landscape;
}

public override UIInterfaceOrientation PreferredInterfaceOrientationForPresentation()
{
    return UIInterfaceOrientation.LandscapeLeft;
}

void RestrictRotation(bool restriction)
{
    AppDelegate app = (AppDelegate)UIApplication.SharedApplication.Delegate;
    app.RestrictRotation = restriction;
}

您可以在 ViewController

中添加以下代码
public override void ViewWillAppear(bool animated)
{
   base.ViewWillAppear(animated);

   AppDelegate appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
   appDelegate.allowRotation = true;

   UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.LandscapeLeft), new NSString("orientation"));
}

public override void ViewWillDisappear(bool animated)
{
   base.ViewWillDisappear(animated);

   AppDelegate appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
   appDelegate.allowRotation = false;

   UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.Unknown), new NSString("orientation"));
}

另外,别忘了勾选info.plist中的需要全屏,否则不会在一些全屏设备上工作(比如 iPad Pro)。