SwiftUI Repaint View Components on Device Rotation

后端 未结 12 1873
谎友^
谎友^ 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:26

    If someone is also interested in the initial device orientation. I did it as follows:

    Device.swift

    import Combine
    
    final class Device: ObservableObject {
        @Published var isLandscape: Bool = false
    }
    

    SceneDelegate.swift

    class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
        var window: UIWindow?
    
        // created instance
        let device = Device() // changed here
    
        func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    
            // ...
    
            // added the instance as environment object here
            let contentView = ContentView().environment(\.managedObjectContext, context).environmentObject(device) 
    
    
            if let windowScene = scene as? UIWindowScene {
    
                // read the initial device orientation here
                device.isLandscape = (windowScene.interfaceOrientation.isLandscape == true)
    
                // ...            
    
            }
        }
    
        // added this function to register when the device is rotated
        func windowScene(_ windowScene: UIWindowScene, didUpdate previousCoordinateSpace: UICoordinateSpace, interfaceOrientation previousInterfaceOrientation: UIInterfaceOrientation, traitCollection previousTraitCollection: UITraitCollection) {
            device.isLandscape.toggle()
        }
    
       // ...
    
    }
    
    
    

提交回复
热议问题