Search code examples
iosxamarinxamarin.iosmvvmcrossuiinterfaceorientation

programmatically change orientation from Landscape to Portrait Mode xamarin IOS


I am developing an app with Xamarin MVVMCross technology and would like to ask a question about InterfaceOrientation option: all view controllers of application support all orientations but one should use only Portrait mode. When I go to that ViewController from others in Portrait mode, I am able to keep my portrait viewcontroller in Portrait mode due to method in my AppDelegate.cs :

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

But when I go to my portraitview controller when device in LandscapeLeft(LandscapeRight) orientations, GetSupportedInterfaceOrientations from AppDelegate.cs method is not called and that view controller is opened in Landscape mode. Is there a way to programmatically change orientation from Landscape to Portrait Mode just for one view controller in Xamarin IOS?

Thank you


Solution

  • In your helper class;

    public static void LockOrientation(UIInterfaceOrientationMask uIInterfaceOrientationMask, UIInterfaceOrientation uIInterfaceOrientation)
            {
                if (UIApplication.SharedApplication.Delegate != null)
                {
                    CommonUtils.LockOrientation(uIInterfaceOrientationMask);
                    UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)uIInterfaceOrientation), new NSString("orientation"));
                }
            }
    

    In AppDelegate.cs

        //Set the orientation for rest of the app
    public UIInterfaceOrientationMask OrientationLock = UIInterfaceOrientationMask.All;
    
                public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations(UIApplication application, UIWindow forWindow)
                {
                    return OrientationLock;
                }
    

    Now simply call the LockOrientation method wherever you would like to lock/change orientation.

    Example:

    CommonUtils.LockOrientation(UIInterfaceOrientationMask.Portrait, UIInterfaceOrientation.Portrait);