简体   繁体   中英

iOS 13 UIWindowScene how to lock orientation?

I want to use SceneDelegate, UIWindowScene, UIWindowSceneDelegate and other UIScene related things.

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }

    window = UIWindow.init(frame: windowScene.coordinateSpace.bounds)
    window?.windowScene = windowScene

    let vc = UIStoryboard(name: "FCBottomTabBar", bundle: nil).instantiateInitialViewController()!
    window?.rootViewController = vc
    window?.makeKeyAndVisible()
}

How can i dynamically lock the orientation for this window? For example for portrait only? Dynamically means that in runtime when user interacts with something the orientation locks back to all.

For example for screen A i need to lock to only portrait orientation. For screen B to only landscape.

From 'Device orientation' initially make it portrait.

In AppDelegate make a variable 'orientation' and set its value to UIInterfaceOrientationMask.portrait

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    ...
    var orientation = UIInterfaceOrientationMask.portrait
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return orientation
    }
}

Now in your desired ViewController write this to change orientation

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    (UIApplication.shared.delegate as! AppDelegate).orientation = .landscapeLeft
    let value = UIInterfaceOrientation.landscapeLeft.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
    
}

Hope it will help you.

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