簡體   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