SwiftUI 禁用视图的自动旋转

SwiftUI disable auto rotation of views

我有一个应该支持横向和纵向的 SwiftUI 应用程序。但是我想要 iOS 中 Camera.app 的行为。当设备旋转时,只有按钮在切换时旋转 landscape/portrait 所有其他内容保持原样。

所以我想禁用某些视图的自动旋转并为某些视图启用旋转。不确定如何实施。

struct ContentView: View {
   var view: some View {
       HStack {
           Text("Hello") // Don't rotate
           Text("World") // Rotate
       }
   }
}

理论上,我尝试 or 检测旋转并在旋转设备时旋转 "Hello" 文本。

我已经尝试使用 link_2 并更改了一些代码,如下所示:

SceneDelegate中:

func windowScene(_ windowScene: UIWindowScene, didUpdate previousCoordinateSpace: UICoordinateSpace, interfaceOrientation previousInterfaceOrientation: UIInterfaceOrientation, traitCollection previousTraitCollection: UITraitCollection) {
        switch windowScene.interfaceOrientation {
        case .landscapeLeft:
            model.angel = 90
        case .landscapeRight:
            model.angel = -90
        case .portraitUpsideDown:
            model.angel = 180
        default:
            model.angel = 0
        }
    }

型号中:

class Model: ObservableObject {
    let objectWillChange = ObservableObjectPublisher()

    var angel: Double = 0 { willSet { objectWillChange.send() } }
}

并且在 ContentView 中:

struct ContentView: View {
    @EnvironmentObject var model: Model

    var body: some View {
        HStack {
            Text("Hello")
                .rotationEffect(Angle(degrees: model.angel))
            Text("World")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

希望对您有所帮助!