Hello,
We can do this by Invoke platform code . Because MAUI do not provide Api to change the page orientation directly.
Firstly, we can create a class about change the DeviceOrientation, then use a method to invoke platform code to change the device orientation.
#if ANDROID
using Android.Content;
using Android.Views;
using Android.Runtime;
#elif IOS
using UIKit;
using Foundation;
#endif
public class DeviceOrientationService
{
public void SeOrientation(DisplayOrientation orientation)
{
#if ANDROID
if (DisplayOrientation.Landscape == orientation)
{
Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.Landscape;
}
else
{
Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
}
#elif IOS
if (UIDevice.CurrentDevice.CheckSystemVersion(16, 0))
{
var windowScene = (UIApplication.SharedApplication.ConnectedScenes.ToArray()[0] as UIWindowScene);
if (windowScene != null)
{
var nav = UIApplication.SharedApplication.KeyWindow?.RootViewController;
if (nav != null)
{
// Tell the os that we changed orientations so it knows to call GetSupportedInterfaceOrientations again
nav.SetNeedsUpdateOfSupportedInterfaceOrientations();
if (DisplayOrientation.Landscape == orientation)
{
windowScene.RequestGeometryUpdate(new UIWindowSceneGeometryPreferencesIOS(UIInterfaceOrientationMask.LandscapeRight), error => { });
}
else
{
windowScene.RequestGeometryUpdate(new UIWindowSceneGeometryPreferencesIOS(UIInterfaceOrientationMask.Portrait), error => { });
}
}
}
}
else
{
if (DisplayOrientation.Landscape == orientation)
{
UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.LandscapeRight), new NSString("orientation"));
}
else
{
UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.Portrait), new NSString("orientation"));
}
}
#endif
}
}
In the end, if we just want to change the Orientation for specific page. We can change the Orientation to Landscape in OnAppearing
method, change the Orientation to Portrait in OnDisappearing
method like following code.
DeviceOrientationService service;
protected override void OnAppearing()
{
service= new DeviceOrientationService();
service.SeOrientation(DisplayOrientation.Landscape);
base.OnAppearing();
}
protected override void OnDisappearing()
{
base.OnDisappearing();
service.SeOrientation(DisplayOrientation.Portrait);
}
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.