Force portrait in SwiftUI except one view

I am developing a SwiftUI project and would like to allow portrait orientation for all but one of the views. For the remaining view, I would like to support both portrait and landscape orientation. Are there any resources available that detail how to accomplish this in SwiftUI?

Yes, there are resources available to accomplish this in SwiftUI.

You can create a custom view controller that supports both portrait and landscape orientation and then use this view controller for the specific view that requires this functionality.

Here’s an example implementation:

  1. Create a custom view controller that supports both portrait and landscape orientation. To do this, you can subclass UIViewController and override the supportedInterfaceOrientations property to return the orientations that you want to support:
class CustomViewController: UIViewController {
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .all
    }
}
  1. In your SwiftUI project, create a UIViewControllerRepresentable for your custom view controller:
struct CustomView: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> CustomViewController {
        return CustomViewController()
    }

    func updateUIViewController(_ uiViewController: CustomViewController, context: Context) {
    }
}
  1. Use your CustomView in the view that requires both portrait and landscape orientation:
struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                Text("Portrait only")
            }
            .navigationBarTitle("Portrait")
        }
        .navigationViewStyle(StackNavigationViewStyle())
        .tabItem {
            Image(systemName: "1.circle")
            Text("Portrait")
        }
        .tag(0)
        .background(CustomView()) // Use CustomView here
    }
}

Note: In this example, the ContentView is using a NavigationView and TabView to demonstrate how to use the CustomView in a real-world scenario. However, you can use the CustomView in any view that requires both portrait and landscape orientation.