SwiftUI Repaint View Components on Device Rotation

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

    This seems to work for me. Then just init and use Orientation instance as environmentobject

    class Orientation: ObservableObject {
            let objectWillChange = ObservableObjectPublisher()
    
            var isLandScape:Bool = false {
                willSet {
                    objectWillChange.send() }
            }
    
            var cancellable: Cancellable?
    
            init() {
    
                cancellable = NotificationCenter.default
                    .publisher(for: UIDevice.orientationDidChangeNotification)
                    .map() { _ in (UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight)}
                    .removeDuplicates()
                    .assign(to: \.isLandScape, on: self)
            }
        }
    

提交回复
热议问题