Rotates any view so that it matches the device orientation if it's in an array of allowed orientations.
Submission for SwiftUISeries - Workarounds & Hacks event
When building Old English Wordhord I wanted the app to be portrait-only but the image view to rotate with the phone. Although this can be done in UIKit, SwiftUI doesn't have a way to control allowed orientations per view.
The app only allows portrait and landscapeLeft orientations but the content can be set to rotate to any number of orientations using the toggles.
- Device orientation is taken from
UIDevice.current.orientation supportedInterfaceOrientationsis taken fromUISupportedInterfaceOrientationsin the app bundleinterfaceOrientationis determined fromdeviceOrientationandsupportedInterfaceOrientationscontentOrientationis determined fromdeviceOrientationandallowedOrientations- Rotation between
interfaceOrientationandcontentOrientationis used to rotate the content view - GeometryReader is used to calculate the size of the space
- Height and width of the content are swapped if there's a 90 degree different between
interfaceOrientationandcontentOrientation .position()modifier is used to center the view- Orientations are updated whenever:
.onAppearallowedOrientationsare changed.orientationDidChangeNotificationfires.willEnterForegroundNotificationfires
This component is available in my Swift package:
