Skip to content

ryanlintott/RotationMatchingOrientation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 

Repository files navigation

RotationMatchingOrientation

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

Why did I make this workaround?

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.

Example

The app only allows portrait and landscapeLeft orientations but the content can be set to rotate to any number of orientations using the toggles.

Example Video

How does it work?

  • Device orientation is taken from UIDevice.current.orientation
  • supportedInterfaceOrientations is taken from UISupportedInterfaceOrientations in the app bundle
  • interfaceOrientation is determined from deviceOrientation and supportedInterfaceOrientations
  • contentOrientation is determined from deviceOrientation and allowedOrientations
  • Rotation between interfaceOrientation and contentOrientation is 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 interfaceOrientation and contentOrientation
  • .position() modifier is used to center the view
  • Orientations are updated whenever:
    • .onAppear
    • allowedOrientations are changed
    • .orientationDidChangeNotification fires
    • .willEnterForegroundNotification fires

Use it in your app

This component is available in my Swift package:

FrameUp Logo

About

Rotates any SwiftUI view to match device orientation

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages