Hello,
You can do this by invoke native platform code in shared code part.
Firstly, you can use Conditional compilation to wrap the native platform code for different platform.
For example, If I have contentpage, I want to set the landscape mode when the page appearing.
For Android, you can set Platform.CurrentActivity.RequestedOrientation = ScreenOrientation.Landscape;
directly.
For iOS, you need to get the RootViewController then set UIInterfaceOrientationMask.LandscapeLeft
.
You can refer to the following code.
#if ANDROID
using Android.Content.PM;
#elif IOS
using Microsoft.Maui.Devices;
using UIKit;
#endif
namespace MauiAppTestInstallPackage;
public partial class NewPage1 : ContentPage
{
public NewPage1()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
#if ANDROID
Platform.CurrentActivity.RequestedOrientation = ScreenOrientation.Landscape;
#elif IOS
if (UIDevice.CurrentDevice.CheckSystemVersion(16, 0))
{
var scene = (UIApplication.SharedApplication.ConnectedScenes.ToArray()[0] as UIWindowScene);
if (scene != null)
{
var uiAppplication = UIApplication.SharedApplication;
var test = UIApplication.SharedApplication.KeyWindow?.RootViewController;
if (test != null)
{
UIInterfaceOrientationMask NewOrientation;
NewOrientation = UIInterfaceOrientationMask.LandscapeLeft;
scene.RequestGeometryUpdate(
new UIWindowSceneGeometryPreferencesIOS(NewOrientation), error => { System.Diagnostics.Debug.WriteLine(error.ToString()); });
test.SetNeedsUpdateOfSupportedInterfaceOrientations();
test.NavigationController?.SetNeedsUpdateOfSupportedInterfaceOrientations();
}
}
}
#endif
}
}
For the iOS, please do not forget to add GetSupportedInterfaceOrientations
method in AppDelegate.cs
like following code.
[Register("AppDelegate")]
public class AppDelegate : MauiUIApplicationDelegate
{
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
[Export("application:supportedInterfaceOrientationsForWindow:")]
public UIInterfaceOrientationMask GetSupportedInterfaceOrientations(UIApplication application, UIWindow forWindow)
{
if (forWindow.WindowScene != null && forWindow.WindowScene.Title == "PerformOrientation")
{
return UIInterfaceOrientationMask.All;
}
else
{
return application.SupportedInterfaceOrientationsForWindow(forWindow);
}
}
}
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.