简体   繁体   English

iOS 13 UIWindowScene如何锁定方向?

[英]iOS 13 UIWindowScene how to lock orientation?

I want to use SceneDelegate, UIWindowScene, UIWindowSceneDelegate and other UIScene related things.我想使用 SceneDelegate、UIWindowScene、UIWindowSceneDelegate 和其他 UIScene 相关的东西。

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?如何动态锁定此 window 的方向? For example for portrait only?例如仅用于portrait 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.例如,对于屏幕 A,我只需要锁定纵向。 For screen B to only landscape.对于屏幕 B 仅横向。

From 'Device orientation' initially make it portrait.从“设备方向”最初使其成为纵向。

In AppDelegate make a variable 'orientation' and set its value to UIInterfaceOrientationMask.portrait在 AppDelegate 中创建一个变量 'orientation' 并将其值设置为 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现在在你想要的 ViewController 中写这个来改变方向

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.希望它会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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