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 appears. But this value doesn't change when the device orientation changes. I need to redraw all components when the user changes the device orientation.
If someone is also interested in the initial device orientation. I did it as follows:
Device.swift
SceneDelegate.swift
@dfd provided two good options, I am adding a third one, which is the one I use.
In my case I subclass UIHostingController, and in function viewWillTransition, I post a custom notification.
Then, in my environment model I listen for such notification which can be then used in any view.
In SceneDelegate.swift:
My UIHostingController subclass:
And my model:
There is an easier solution that the one provided by @kontiki, with no need for notifications or integration with UIKit.
In SceneDelegate.swift:
In Model.swift:
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.I tried some of the previous answers, but had a few problems. One of the solutions would work 95% of the time but would screw up the layout every now and again. Other solutions didn't seem to be in tune with SwiftUI's way of doing things. So I came up with my own solution. You might notice that it combines features of several previous suggestions.
I think easy repainting is possible with addition of
to View struct.
I have such example:
As you can see I need to recalculate tabBarHeight to apply correct bottom padding on Extra View, and addition of this property seems to correctly trigger repainting.
With just one line of code!