纵向 iPhone 应用在 iPad 上以横向启动时出现错误边界

Wrong bounds when portrait iPhone app launched on iPad with landscape orientation

我在没有故事板的情况下以编程方式创建视图控制器。该应用程序仅支持“纵向设备方向(在项目常规设置中选中)”。

当应用程序以纵向启动时,它有一个正确的边界 (0.0, 0.0, 375.0, 667.0);但是,当应用程序在 iPad 上以横向启动时,边界会更改为 (0.0, 0.0, 667.0, 375.0) 并倾斜以编程方式设置的自动布局约束。

从下面的屏幕截图可以看出,导航栏中的标题以及视图中的所有内容都不再居中。

func scene(_ scene: UIScene, willConnectTo _: UISceneSession, options _: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    guard let windowScene = (scene as? UIWindowScene) else { return }

    print(">>>", windowScene.coordinateSpace.bounds)
        
    window = UIWindow(frame: windowScene.coordinateSpace.bounds)
    window?.windowScene = windowScene
    window?.rootViewController = MyViewController()
    window?.makeKeyAndVisible()
}

如果 window 以 none 纵向方向开始,解决方法是切换边界宽度和高度。

func scene(_ scene: UIScene, willConnectTo _: UISceneSession, options _: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    guard let windowScene = (scene as? UIWindowScene) else { return }

    var bounds = windowScene.coordinateSpace.bounds
    let isPortrait = windowScene.interfaceOrientation.isPortrait
        
    if !isPortrait {
        let width = bounds.height
        let height = bounds.width
            
        bounds = CGRect(x: 0, y: 0, width: width, height: height)
    }

    window = UIWindow(frame: bounds)
    window?.windowScene = windowScene
    window?.rootViewController = MyViewController()
    window?.makeKeyAndVisible()
}