SwiftUI Locking View Rotation

Apple needs to support locking a SwiftUI View into a particular orientation like .portrait or .landscape. The work arounds to support this feature are complicated and keep getting deprecated by Apple.

You need this feature to support the Camera at least which is another sore topic since it's poorly supported in SwiftUI presently.

All that is needed is an orientation var like UIDevice.current.orientation, but excluding .faceUp and .faceDown so it only returns .portrait or .landscape orientations. If the device goes into .faceUp it should just return the previous orientation.

Then a View extension like detectOrientation(_ orientation: Binding<UIDeviceOrienation>) to detect the current views orientation so this can be used like : if orientation.isLandscape { //SwiftUI landscape elements } else { //SwiftUI portrait elements }

Then another method .lockOrientation(_ orientation:UIDeviceOrienation)

Now a SwiftUI can get the current orientation with : .detectionOriention($orientation) And lock a SwiftUI view : .lockOrientation(.portrait)

The SwiftUI SubViews within the Primary View would then just consume the orientation var to layout properly in Landscape or Portrait.

When Apple implements a SwiftUIController to manage SwiftUI views ... just kidding. You need to implement an AppDelegate with the prefered interface orientations and set it as the app delegate for your swift ui application, hopefully it should work:

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        .portrait
    }
}

Then in your swiftui @main app

import UIKit
import SwiftUI

@main
struct SampleApp: App {
    
    @UIApplicationDelegateAdaptor var appDelegate: AppDelegate
    
    var body: some Scene { ... }
}

With some work, you can begin to architect updates between the AppDelegate and the SwiftUI App into the SwiftUI Environment for all views to have whatever data you will need.

SwiftUI Locking View Rotation
 
 
Q