Xcode 13 + SwiftUI 项目取消勾选竖屏后无法强制应用仅横屏运行
问题原因
- 若应用支持iPad设备且未开启「Requires full screen」选项,iOS为适配分屏多任务特性会强制应用支持所有界面方向,项目设置中勾选的方向限制会直接失效。
- 若使用iOS14+引入的SwiftUI原生App生命周期(无AppDelegate/SceneDelegate文件),部分系统版本下全局方向配置无法正确作用于SwiftUI根视图,需要额外代码控制。
解决步骤
基础配置校验
- 打开项目设置的「General」标签页,找到「Deployment Info」区域
- 确认iPhone和iPad的设备方向都仅勾选需要的横屏选项(Landscape Left、Landscape Right),取消勾选Portrait、Upside Down
- 若支持iPad设备,必须勾选「Requires full screen」选项,否则方向限制会被多任务逻辑覆盖无法生效
- 打开Info.plist文件,确认「Supported interface orientations」和「Supported interface orientations (iPad)」两个配置项下仅保留横屏相关取值,删除竖屏相关条目
代码层面强制方向控制(针对SwiftUI生命周期)
如果完成基础配置后问题仍存在,添加以下代码强制控制方向:
- 在App入口文件中添加自定义AppDelegate绑定:
import SwiftUI @main struct YourAppNameApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } } } class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { return .landscape } }
- 如果需要实现竖屏时内容顺时针旋转90度的提示效果,修改ContentView代码如下:
import SwiftUI struct ContentView: View { @State private var isPortrait = UIDevice.current.orientation.isPortrait var body: some View { Text("Hello, world!") .padding() .rotationEffect(isPortrait ? .degrees(90) : .degrees(0)) .animation(.easeInOut, value: isPortrait) .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in isPortrait = UIDevice.current.orientation.isPortrait } } }
内容的提问来源于stack exchange,提问作者mkto
相关产品推荐
相关产品推荐

