Reacting to device rotation
SwiftUI does not have a built-in way of detecting device rotation and displaying different information depending on device orientation. However, it is possible to subscribe to the notification for the event using UIDevice.orientationDidChangeNotification
, and to decode the device orientation when we receive the system notification.
We create our own view modifier that listens to this event and have it call a function when this happens. As a parameter to this function, we will include the UIDeviceOrientation
value, because we need to be able to react differently to different orientations. In our example, we will decode all possible values for the orientation and visualize a different text in each case.
The following example illustrates this technique:
import SwiftUI struct RotationModifier: ViewModifier { let action: (UIDeviceOrientation) -> Void func body(content: Content) -> some View { ...