簡體   English   中英

Xcode & Swift - 無法從 AppDelegate 實例化另一個視圖 controller

[英]Xcode & Swift - unable to instantiate another view controller from AppDelegate

在這個應用程序中,當您第一次使用它時,您會獲得 3 個歡迎頁面。 在最后一個之后,我在 UserDefaults 中將 bool 保存為 true,以便在用戶下次啟動應用程序時跳過這些歡迎頁面。

為此,在 AppDelegate.swift 中,我執行以下操作:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        if UserDefaultsVault.shared.getDidFinishIntro() == true {

            self.window = UIWindow(frame: UIScreen.main.bounds)
            let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

            let mainVC = storyboard.instantiateViewController(withIdentifier: "mainPage") as UIViewController

            self.window?.rootViewController = mainVC
            self.window?.makeKeyAndVisible()

        } 

        return true
    }

我當然在 storyboard 中將 storyboard ID 添加到我的視圖 controller 中,並且我還檢查了斷點是否滿足條件(這是真的)。

盡管如此, Main Controller 不會實例化。

我用這段代碼制作了另一個應用程序,它總是有效的!

我是不是弄錯了什么?

對於 iOS 13+,您需要在 SceneDelegate 中提供instantiateViewController(withIdentifier:) ,如下所示:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

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

        if UserDefaultsVault.shared.getDidFinishIntro() {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            window?.rootViewController = storyboard.instantiateViewController(withIdentifier: "mainPage")
        }
    }
}

注意:您的代碼適用於使用以下 iOS 13 的設備。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM