Xcode和Swift-无法从AppDelegate实例化另一个视图控制器

问题描述 投票:0回答:1

在您首次使用此应用程序时,您会获得3个欢迎页面。在最后一个之后,我在UserDefaults中将布尔值保存为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
    }

我当然将情节提要ID添加到情节提要中的视图控制器中,并且还检查了断点是否满足条件(这是事实)。

尽管如此,主控制器不会实例化。

我使用此代码制作了另一个应用程序,它始终可以正常工作!

我是否犯了错?

swift xcode nsuserdefaults appdelegate
1个回答
1
投票

对于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的设备。

© www.soinside.com 2019 - 2024. All rights reserved.