15

Environment: SwiftUI using Swift 5.3
Scenario: The default orientation is Portrait, LandscapeLeft & LandscapeRight per Xcode General Setting.
This allows the possibility to have landscape on demand versus having the Xcode Setting to Portrait only.
The project is using SwiftUI Lifecycle vs AppDelegate.

Goal: To have ONLY particular Views able to rotate to landscape; the majority locked in portrait.

Current Modus Operandi: The device is set for Portrait-Only mode within the current View's .upAppear{} and via onReceive{} via the device Orientation-Change Notification.

I found this the only way to actually do a momentary Portrait lock, allowing others to render for landscape.

Problem: The Orientation-Change Notification happens TOO LATE: I see the actual landscape being corrected in real time - so the image snaps back during the rotate.

Question: How to I lock a specific swiftUI View in Portrait mode, allowing others to freely change orientation?

import SwiftUI
import UIKit

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.blue
            NavigationView {
                Text("Hello, world!")
                    .padding()
                    .navigationTitle("Turkey Gizzards")
                    .navigationBarTitleDisplayMode(.inline)
            }
        }.onAppear {
            UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
        }.onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
            UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
        }
    }
}
1
  • the things that you are asking is impossible because they are lock down after lunching app in info.plist, but you can artificially rotate your content to reaching what you want
    – ios coder
    Feb 4, 2021 at 0:55

4 Answers 4

28

There is no native SwiftUI method for doing that. It looks like for now, it is mandatory to use the AppDelegate adaptor.

Inside your App main, add this:

@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

Then add this class:

class AppDelegate: NSObject, UIApplicationDelegate {
        
    static var orientationLock = UIInterfaceOrientationMask.all //By default you want all your views to rotate freely

    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return AppDelegate.orientationLock
    }
}

And in the specific view designed to be locked in portrait mode:

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.blue
            NavigationView {
                Text("Hello, world!")
                    .padding()
                    .navigationTitle("Turkey Gizzards")
                    .navigationBarTitleDisplayMode(.inline)
            }
        }.onAppear {
            UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation") // Forcing the rotation to portrait
            AppDelegate.orientationLock = .portrait // And making sure it stays that way
        }.onDisappear {
            AppDelegate.orientationLock = .all // Unlocking the rotation when leaving the view
        }
    }
}

You may also, depending on your needs, add another UIDevice.current.setValue(UIInterfaceOrientation.yourOrientation.rawValue, forKey: "orientation") inside the onDisappear to force the rotation when leaving the view.

7
  • I tried 'UIDevice.curret.setValue...' which worked but it didn't freeze the orientation as I had hoped, it merely yanked the orientation back to the original; not what the user would like beyond initial amusement. Feb 10, 2021 at 2:07
  • That's why AppDelegate.orientationLock = .portrait should lock it.
    – Lawris
    Feb 10, 2021 at 18:49
  • 1
    I'm using the SwiftUI App lifecycle. I tried to access the UIApp Delegate; but I got a compiler error stating UIApp Delegate: 'Value of type 'AppDelegate' has no member 'orientationLock'', Feb 11, 2021 at 3:17
  • i get cannot find AppDelegate in scope upon using the exact code above
    – TechyGod
    Jul 2, 2022 at 15:22
  • 1
    Turns out this solution is discouraged / no longer works. stackoverflow.com/questions/75594819/… Mar 15 at 14:02
5

Are you using UIHostingController? Another workaround might be subclassing it to implement supportedInterfaceOrientations / shouldAutorotate as we might normally do in UIKit:

class HostingController<Content>: UIHostingController<Content> where Content: View {}
3

The provided solutions were not working on iOS 16 and I cleaned up the SwiftUI implementation.

My solution rotates to the correct orientation and locks the rotation. The default is portrait and forces landscape on specific views. This can be changed to your needs.


In the AppDelegate add:

static var orientationLock = UIInterfaceOrientationMask.portrait {
    didSet {
        if #available(iOS 16.0, *) {
            UIApplication.shared.connectedScenes.forEach { scene in
                if let windowScene = scene as? UIWindowScene {
                    windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: orientationLock))
                }
            }
            UIViewController.attemptRotationToDeviceOrientation()
        } else {
            if orientationLock == .landscape {
                UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
            } else {
                UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
            }
        }
    }
}

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return AppDelegate.orientationLock
}

Create a View+Extensions and add the following code:

extension View {
    @ViewBuilder
    func forceRotation(orientation: UIInterfaceOrientationMask) -> some View {
        self.onAppear() {
            AppDelegate.orientationLock = orientation
        }
        // Reset orientation to previous setting
        let currentOrientation = AppDelegate.orientationLock
        self.onDisappear() {
            AppDelegate.orientationLock = currentOrientation
        }
    }
}

Then in SwiftUI you can do:

struct DummyView: View {
    var body: some View {
        ZStack {
            Text("Dummy View")
        }.forceRotation(orientation: .landscape)
    }
}
3
  • Hello, This method runs the orientation after the swiftUI view is created. It works after view returns. It should work without going to Zstack. Do you have an idea?
    – ikbal
    Jan 16 at 20:21
  • Why do we need app delegate here? We can get away with a global orientation variable? Feb 9 at 9:23
  • 1
    In iOS16 the setValue technique no longer works :_( stackoverflow.com/questions/75594819/… Mar 15 at 17:06
0

So in SwiftUI Apple has tried to force you to use just the Info.plist and Xcode General Deployment Info to force the view orientations. They don't support locking a SwiftUI view into a particular orientation which is ridiculous especially if your're using the camera. They also keep depcrecating orientation vars. So to get around these issues is complicated, but the code below works.

In AppDelegate have this.

static var orientationLock = UIInterfaceOrientationMask.all 
static var deviceOrientation = UIDeviceOrientation.landscapeRight

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
     return AppDelegate.orientationLock
}

Now you need a SwiftUI View Extension

extension View {
   func detectOrientation(_ binding: Binding<UIDeviceOrientation>) -> some View {
     self.modifier(OrientationDetector(orientation: binding))
  }
}

struct OrientationDetector: ViewModifier {
  @Binding var orientation: UIDeviceOrientation
  let orientationMask = AppDelegate.orientationLock
  func body(content: Content) -> some View {
    content
      .onReceive(NotificationCenter.default.publisher(for:     UIDevice.orientationDidChangeNotification)) { _ in

      if checkOrientation(orientationMask: orientationMask)
      {
          orientation = UIDevice.current.orientation
      }
      else
      {
          orientation = AppDelegate.deviceOrientation
      }
  }
 }
}

Now it gets tricky since UIDevice.current.orientation has .faceUp and .faceDown which you don't care about so you need to ignore these view orientations, this is effectively what the checkOrienation() method does by saving the prior orientation when it does go into .faceUp or .faceDown.

func checkOrientation(orientationMask:UIInterfaceOrientationMask) -> Bool
{
//Here we're ignoring faceUp and faceDown and storing the prior orientation in AppDelegate.deviceOrientation
//This effectively eliminates these two problematic orientations so the App will ignore these and return the prior value
var status : Bool = false
switch UIDevice.current.orientation {
case .portrait :
    if(orientationMask == .portrait || orientationMask == .portraitUpsideDown || orientationMask == .allButUpsideDown)
    {
        status = true
        AppDelegate.deviceOrientation = UIDevice.current.orientation
    }
case .landscapeLeft :
    if orientationMask == .landscapeLeft || orientationMask == .allButUpsideDown
    {
        status = true
        AppDelegate.deviceOrientation = UIDevice.current.orientation
    }
case .landscapeRight :
    if orientationMask == .landscapeRight || orientationMask == .allButUpsideDown
    {
        status = true
        AppDelegate.deviceOrientation = UIDevice.current.orientation
    }
case .portraitUpsideDown :
    if orientationMask == .portraitUpsideDown || orientationMask == .allButUpsideDown
    {
        status = true
        AppDelegate.deviceOrientation = UIDevice.current.orientation
    }
case .faceUp :
    status = false
    
case .faceDown :
    status = false
    
case .unknown:
    status = false

@unknown default:
    status = false

}
return status
}

Now in your Primary SwiftUI Views you need an init and .detectOrienation($orientation)

  @State private var orientation = UIDevice.current.orientation 


init() {

    //Lock into all view rotations
    AppDelegate.orientationLock = .allButUpsideDown
    if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
        windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: .allButUpsideDown))
       UIApplication.navigationTopViewController()?.setNeedsUpdateOfSupportedInterfaceOrientations()
    }
}

 //At bottom of SwiftUI view add this :
 .detectOrientation($orientation)

What the above does for the SwiftUI View is let it rotate for .allButUpsideDown view rotations. If you want to lock it, set .portrait, or .landscapeLeft or .landscapeRight.

The Primary SwiftUI View will declare the @State var orientation, and all your SwiftUI SubViews that need orientation need to consume this same var.

Thus a SwiftUI Subview needs this :

 @Binding private var orientation:UIDeviceOrientation

 init(orientation:Binding<UIDeviceOrientation>)
          self._orientation = orientation
 }

Now in your Primary and SubViews you do this to handle the layout in a particular view orientation.

if orientation.isLandscape {

  //SwiftUI elements for Landscape

} else {

  //SwiftUI elements for Portrait

} 

And thats it, it's a lot of code to get around this problem, but it works in SwiftUI version 5 and iOS 16+ and Apple will approve it for an App Release also.

We really need to lobby Apple to support natively locking a SwiftUI View into a particular view orientation, this can be done by just calling a simple SwiftUI method. They also need to create a new var for UIDeviceOrientation that ignores .faceUp and .faceDown so you can consume this var in your SWiftUI view and layout your view elements accordingly.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.