For my app working on iPhone and IPad, I have two different designs depending on the landscape or portrait orientation.
But it's not so simple, because for iPad, the design is the same while in portrait or landscape orientation.
So I thought to user verticalSizeClass. If it is compact, I apply portrait design, if it is Regular, I apply landscape design.
So I introduce the environment variable:
@Environment(\.verticalSizeClass) var verticalSizeClass: UserInterfaceSizeClass?
And create the following modifier (found on Apple Developper Forum)
struct DeviceRotationViewModifier: ViewModifier {
let action: (UIDeviceOrientation) -> Void
func body(content: Content) -> some View {
content
.onAppear()
.onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
action(UIDevice.current.orientation)
}
}
}
// A View wrapper to make the modifier easier to use
extension View {
func onRotate(perform action: @escaping (UIDeviceOrientation) -> Void) -> some View {
self.modifier(DeviceRotationViewModifier(action: action))
}
}
Implementing the OnRotate modifier on my contentView
.onRotate { newOrientation in
print(verticalSizeClass)
}
I find that the verticalSizeClass is not correct on first call of OnRotate (it's always regular). After when I change orientation, the verticalsizeClass becomes correct.
What did I missed?