在我的应用程序中,所有 View 都通过 info.plist 强制为纵向。
异常(exception)应该是“MyView”,它应该始终处于横向方向。
深入研究 SO 后我做了什么:
在 AppDelegate.swift 中添加:
static var orientationLock = UIInterfaceOrientationMask.portrait
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return AppDelegate.orientationLock
}
MyView.swift
struct MyView: View {
var body: some View {
ZStack {
// ...Some Images, etc.
}
.onAppear(perform: orientationLandscape)
.onDisappear(perform: orientationPortrait)
}
func orientationLandscape() {
AppDelegate.orientationLock = UIInterfaceOrientationMask.landscapeRight
UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight, forKey: "orientation")
UINavigationController.attemptRotationToDeviceOrientation()
}
func orientationPortrait() {
AppDelegate.orientationLock = UIInterfaceOrientationMask.portrait
UIDevice.current.setValue(UIInterfaceOrientation.portrait, forKey: "orientation")
UINavigationController.attemptRotationToDeviceOrientation()
}
}
UIDevice.current.setValue 产生错误。 如果没有这条线,我可以通过将设备保持横向/纵向来手动更改 MyView 中的方向,但在打开和关闭 View 时它应该自动切换。
最佳答案
我通过定位 bmjohns answer 解决了这个问题关于类似的问题:
- 在 AppDelegate 中添加一些代码(这部分我已经有了)
- 创建一个完成这项工作的结构体和函数(需要对 XCode 11 和 SwiftUI 进行小调整)
- 执行 View 的 onAppear 函数
关于ios - 在一个 View 中强制横向方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60755275/