首页 > 解决方案 > 如何为在 iPad 上运行的 iPhone SwiftUI 应用程序锁定纵向方向?

问题描述

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

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

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
    }
}

iPhone按预期工作:

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

iPad 不遵守方向锁定:

纵向模式下的 iPad 横向模式下的 iPad

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

<key>UISupportedInterfaceOrientations</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
</array>

然后我定义了一个 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()
        }
    }
}

有趣的是:

我正在使用 Xcode 12.5 和 Swift 5。

标签: iosswiftiphoneipadswiftui

解决方案


在此处输入图像描述

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


推荐阅读