Xamarin.Forms: Force Screen Rotation on iOS 16

48 Views Asked by At

I want my Xamarin.Forms App to launch the Login Page in Portrait Mode.

On Android everything works perfectly fine, but since iOS 16 the approach to force the screen orientation just doesn't want to work for me and I can't seem to find out why

My AppDelegate.cs:

public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations(UIApplication application, UIWindow forWindow)
    {

        var mainPage = Xamarin.Forms.Application.Current.MainPage;

        if (mainPage is LoginPage || (mainPage is NavigationPage &&
                                       ((NavigationPage)mainPage).CurrentPage is LoginPage) || (mainPage.Navigation != null &&
                                                                                                 mainPage.Navigation.ModalStack.LastOrDefault() is LoginPage))
        {
            return UIInterfaceOrientationMask.Portrait;
        }
        else
        {
            return UIInterfaceOrientationMask.Landscape;
        }
    }

My InterfaceOrientationService.cs, that gets called in the OnAppearing() method in the code behind of my Login Page:

  public void SetPortrait()
    {

        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)
                {
                    nav.SetNeedsUpdateOfSupportedInterfaceOrientations();
                    windowScene.RequestGeometryUpdate(
                        new UIWindowSceneGeometryPreferencesIOS(UIInterfaceOrientationMask.Portrait),
                        error => { }
                    );
                }
            }
        }
        else
        {
            UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.Portrait), new NSString("orientation"));
        }
    }

There are no errors. The code runs through smoothly, but never changes the orientation. Checking the windowScene after stepping out of the method shows that the orientation is still landscape and did not change at all.

Also, GetSupportedInterfaceOrientations in my AppDelegate never gets called.

0

There are 0 best solutions below