SwiftUI Repaint View Components on Device Rotation

后端 未结 12 1898
谎友^
谎友^ 2020-12-01 01:00

How to detect device rotation in SwiftUI and re-draw view components?

I have a @State variable initialized to the value of UIScreen.main.bounds.width when the first

12条回答
  •  甜味超标
    2020-12-01 01:35

    I got

    "Fatal error: No ObservableObject of type SomeType found"

    because I forgot to call contentView.environmentObject(orientationInfo) in SceneDelegate.swift. Here is my working version:

    // OrientationInfo.swift
    final class OrientationInfo: ObservableObject {
        @Published var isLandscape = false
    }
    
    // SceneDelegate.swift
    var orientationInfo = OrientationInfo()
    
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // ...
        window.rootViewController = UIHostingController(rootView: contentView.environmentObject(orientationInfo))
        // ...
    }
    
    func windowScene(_ windowScene: UIWindowScene, didUpdate previousCoordinateSpace: UICoordinateSpace, interfaceOrientation previousInterfaceOrientation: UIInterfaceOrientation, traitCollection previousTraitCollection: UITraitCollection) {
        orientationInfo.isLandscape = windowScene.interfaceOrientation.isLandscape
    }
    
    // YourView.swift
    @EnvironmentObject var orientationInfo: OrientationInfo
    
    var body: some View {
        Group {
            if orientationInfo.isLandscape {
                Text("LANDSCAPE")
            } else {
                Text("PORTRAIT")
            }
        }
    }
    

提交回复
热议问题