如何锁定在 iPad 上运行的 iPhone SwiftUI 应用程序的纵向方向?

Dom*_*nik 4 iphone ipad ios swift swiftui

我有一个仅适用于 iPhone 的 SwiftUI 应用程序,其方向锁定为纵向,效果非常好。但是,当同一个应用程序在 iPad 上运行时(在模拟模式下;iPad 不是目标),锁定不起作用:UI 随设备旋转,这是无意的,因为它会破坏 UI。它在模拟器和实际设备上都会失败。

我可以使用只有一个视图的空 SwiftUI 项目来重现此问题:

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
    }
}
Run Code Online (Sandbox Code Playgroud)

iPhone 按预期工作:

iPhone 处于纵向模式 iPhone 处于横向模式

iPad 不尊重方向锁定:

iPad 纵向模式 iPad 横屏模式

我的 Info.plist 中有以下内容,但没有成功。iPad 上的 UI 仍然旋转。

<key>UISupportedInterfaceOrientations</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
</array>
Run Code Online (Sandbox Code Playgroud)

然后我定义了一个AppDelegate。仍然没有成功,UI 在 iPad 上不断旋转。

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.portrait
    }
}

@main
struct orientationApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有趣的是:

  • 当我启用 iPad 作为目标时,方向锁定开箱即用。但是,我不想提供适用于 iPad 的应用程序。我只是想为故意在 iPad 上安装 iPhone 应用程序的用户修复 UI。
  • 当我在 iPhone 上测试 AppDelegate 方法时,即使我允许 Info.plist 中的所有设备方向,它也能工作,所以它似乎做了正确的事情(只是在 iPad 上不行)。

我正在使用 Xcode 12.5 和 Swift 5。

i4g*_*uar 5

在此输入图像描述

取消勾选Supports multiple windows解决了我的问题