繁体   English   中英

iOS 13 UIWindowScene如何锁定方向?

[英]iOS 13 UIWindowScene how to lock orientation?

我想使用 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()
}

如何动态锁定此 window 的方向? 例如仅用于portrait 动态意味着在运行时当用户与某物交互时,方向锁定回所有。

例如,对于屏幕 A,我只需要锁定纵向。 对于屏幕 B 仅横向。

从“设备方向”最初使其成为纵向。

在 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
    }
}

现在在你想要的 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")
    
}

希望它会帮助你。

暂无
暂无

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

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