ios - 在一个 View 中强制横向方向

标签 ios swift swiftui device-orientation

在我的应用程序中,所有 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 解决了这个问题关于类似的问题:

  1. 在 AppDelegate 中添加一些代码(这部分我已经有了)
  2. 创建一个完成这项工作的结构体和函数(需要对 XCode 11 和 SwiftUI 进行小调整)
  3. 执行 View 的 onAppear 函数

关于ios - 在一个 View 中强制横向方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60755275/

相关文章:

ios - 关闭部分 iPhone 屏幕

swift - Core Image 过滤后的图像从 iOS 10 上的 UIImageView 中跳出

ios - 当用作 DocumentGroup 的工具栏修饰符中的按钮修饰符时,SwiftUI fileExporter 不存在

ios - 如何使用 swift 创建聊天应用程序

html - swift 。显示来自网站的图像 (xxx.?action=stream)

ios - 如何使用ImagePicker获取图片名称?我得到图像名称,但它只能在模拟器中使用,不能在实际设备中使用

swift - semanticContentAttribute 不再适用于默认的 UITableViewCells

ios - 数组?没有名为 "Generator"的成员

SwiftUI 从配置文件选项卡栏项目进行导航的最佳方式

ios - 根据 SwiftUI 中的切换值更改文本