简体   繁体   中英

How to lock screen orientation for the iPad SwiftUI

I've been force locking the screen orientation using this, which works fine on iPhone simulators:

@main
struct MainApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
    WindowGroup {
        ContentView()
    }
}
}

class AppDelegate: NSObject, UIApplicationDelegate {

static var orientationLock = UIInterfaceOrientationMask.all

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

And used on a view like so:

struct ContentView : View {
var body : some View {
ZStack {
Text("Hello World!")
                        .onAppear{
                                           UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
                        AppDelegate.orientationLock = .portrait
                    }.onDisappear{
                        UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
                        AppDelegate.orientationLock = .portrait
                    }
}
}
}

However, this doesn't work on iPad simulators. It is not enough to deselect orientations in target's Deployment Info because some views have to be different orientations. Any advice would be greatly appreciated!

Click on your project on the left section in Xcode and then you can scroll down till you see "Deployment info". From there you can lock the app screen orientation both in iPhone and iPad在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM