SwiftUI Repaint View Components on Device Rotation

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

    Here‘s an idiomatic SwiftUI implementation based on a notification publisher:

    struct ContentView: View {
        
        @State var orientation = UIDevice.current.orientation
    
        let orientationChanged = NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)
            .makeConnectable()
            .autoconnect()
    
        var body: some View {
            Group {
                if orientation.isLandscape {
                    Text("LANDSCAPE")
                } else {
                    Text("PORTRAIT")
                }
            }.onReceive(orientationChanged) { _ in
                self.orientation = UIDevice.current.orientation
            }
        }
    }
    

    The output of the publisher (not used above, therefor _ as the block parameter) also contains the key "UIDeviceOrientationRotateAnimatedUserInfoKey" in its userInfo property if you need to know if the rotation should be animated.

提交回复
热议问题