Setting Orientation in Xamarin iOS

Image Title

posted by Dom Benoscek
on Aug 24, 2014

You have created an App that should use a single, fixed Orientation when displaying all but one of your views. For example, your app should display in Portrait for all views except for the “Video” view which should display in Portrait, Landscape Left, and Landscape Right. After scouring the web for answers you have found some information but it isn’t consistent and while it may work in the simulator it won’t on an actual device.

iOS version: 7 (verified) and should work on 6

Language: Built in C# for Xamarin but the solution can be translated to Objective-C

Just Show Me Already

Right-click on your iOS project and select “Options” from the dropdown. Select “iOS Application” from the left panel. Choose all of the Orientations from the “Supported Device Orientations” section that the user will (at any point in the App lifecycle) be able to use. In the example referenced above, we would want to select Portrait, Landscape Left, and Landscape Right even though our App will be viewed primarily in Portrait mode.

 

ios-supported-device-orientations

 

Add the following method to your AppDelegate.cs file. Remember to update the returned UIInterfaceOrientationMask to meet your specific needs. Big thanks to Rolf Bjarne Kvinge for explaining and documenting this in the Xamarin bug tracking system: https://bugzilla.xamarin.com/show_bug.cgi?id=13966

 

[Export (“application:supportedInterfaceOrientationsForWindow:”)]

public UIInterfaceOrientationMask GetSupportedInterfaceOrientations (UIApplication application, IntPtr forWindow)

{

    return UIInterfaceOrientationMask.AllButUpsideDown;

}

 

Add the following methods to each of your View Controller classes in which the Orientation should be restricted to Portrait. Remember to update the returned UIInterfaceOrientationMask to meet your specific needs.

 

#region orientation

 

public override bool ShouldAutorotate()

{

    return false;

}

 

public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()

{

    return UIInterfaceOrientationMask.Portrait;

}

 

#endregion

 

Add the following methods to each of your View Controller classes in which the Orientation should be set to all defined orientations. Remember to update the returned UIInterfaceOrientationMask to meet your specific needs.

 

#region orientation

 

public override bool ShouldAutorotate()

{

    return true;

}

 

public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()

{

    return UIInterfaceOrientationMask.AllButUpsideDown;

}

 

#endregion