iOS 16 场景方向问题

当我尝试在我的控制器上只允许纵向方向时,我总是收到此错误:错误域 = UISceneErrorDomain Code = 101“视图控制器不支持请求的方向。请求:landscapeLeft;支持:纵向” UserInfo = {NSLocalizedDescription =视图控制器不支持任何请求的方向。要求:景观左;支持:肖像}

I called this method:
func updateOrientation(orientation: UIInterfaceOrientationMask) {
        if #available(iOS 16, *) {
            DispatchQueue.main.async {
                let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
                self.setNeedsUpdateOfSupportedInterfaceOrientations()
                self.navigationController?.setNeedsUpdateOfSupportedInterfaceOrientations()
                windowScene?.requestGeometryUpdate(.iOS(interfaceOrientations: orientation)) { error in
                    print(error)
                    print(windowScene?.effectiveGeometry )
                }
            }
        }
    }

Did someone face the same issue ?
stack overflow iOS 16 Scene orientation issue
原文答案

答案:

作者头像

在 Appdelegate 中尝试

  • (UIInterfaceOrientationMask)application:(UIApplication )application supportedInterfaceOrientationsForWindow:(UIWindow )window { return UIInterfaceOrientationMaskAll; }
作者头像

是的,我遇到了同样的问题并解决了如下。提供的错误清楚地表明我们正在尝试旋转设备,我们将其限制为仅在以前应用程序某处的一种模式下使用。就我而言,我在 Appdelegate.swift 中实现了以下方法

var myOrientation: UIInterfaceOrientationMask = .portrait

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { return myOrientation }

因此将其限制为仅使用纵向模式,导致应用程序在横向模式下的旋转失败。

通过将方向更改为所有,使其工作。

var myOrientation: UIInterfaceOrientationMask = .portrait
作者头像

J.Y.527 找到了解决方案: https://stackoverflow.com/a/73735976/2858994

它看起来像一个解决方法,但它解决了我的问题。

诀窍是在需要旋转时更新 AppDelegate 支持的方向。

 static func SwitchOrientation(orientation : UIInterfaceOrientationMask, viewController : UIViewController){

    if #available(iOS 16.0, *) {
        (UIApplication.shared.delegate as? AppDelegate)?.orientation = orientation

        let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
        windowScene?.requestGeometryUpdate(.iOS(interfaceOrientations: orientation))

        UIApplication.navigationTopViewController()?.setNeedsUpdateOfSupportedInterfaceOrientations()

        DispatchQueue.main.async {
                    let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
                    viewController.setNeedsUpdateOfSupportedInterfaceOrientations()
                    viewController.navigationController?.setNeedsUpdateOfSupportedInterfaceOrientations()
                    windowScene?.requestGeometryUpdate(.iOS(interfaceOrientations: orientation)) { error in
                        print(error)
                        print(windowScene?.effectiveGeometry ?? "")
                    }
                }

    } else{
        UIDevice.current.setValue(orientation, forKey: "orientation")
    }

}