SwiftUI Repaint View Components on Device Rotation

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

    There is an easier solution that the one provided by @kontiki, with no need for notifications or integration with UIKit.

    In SceneDelegate.swift:

        func windowScene(_ windowScene: UIWindowScene, didUpdate previousCoordinateSpace: UICoordinateSpace, interfaceOrientation previousInterfaceOrientation: UIInterfaceOrientation, traitCollection previousTraitCollection: UITraitCollection) {
            model.environment.toggle()
        }
    

    In Model.swift:

    final class Model: ObservableObject {
        let objectWillChange = ObservableObjectPublisher()
    
        var environment: Bool = false { willSet { objectWillChange.send() } }
    }
    

    The net effect is that the views that depend on the @EnvironmentObject model will be redrawn each time the environment changes, be it rotation, changes in size, etc.

提交回复
热议问题