2

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

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

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

4

2 回答 2

0

这个其他答案似乎过于复杂,并且使用了私有 API。在视图控制器中,要设置支持的方向,只需覆盖supportedInterfaceOrientations.

例如,要将其锁定为纵向:

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    .portrait
}
于 2021-09-19T23:25:57.410 回答
0

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

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

希望它会帮助你。

于 2020-06-28T18:16:57.283 回答