DotNetUser
DotNetUser

Reputation: 455

Orientation lock is not working in xamarin ios

I have to lock the single viewcontroller to landscape and other viewcontroller rotate all side. I have tried the below code. But the view orientation is not changed as landscape. Please give your suggestions.

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;
}

Upvotes: 4

Views: 1252

Answers (1)

Lucas Zhang
Lucas Zhang

Reputation: 18861

You could add the following code in the 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"));
}

In addition , don't forget to check the requires full screen in info.plist , otherwise it won't work on some full screen device (like iPad Pro).

enter image description here

Upvotes: 3

Related Questions