2

我正在尝试在 SceneDelegate 中设置我的入职屏幕。

当我运行下面的代码时,它会编译,但只是进入黑屏。

它们是 AppDelegate 的许多很棒的入门教程,但对于 iOS13 的新 SceneDelegate 来说却很少。我学习了本教程并尝试将其应用于 SceneDelegate,但我无法让它工作:https ://www.youtube.com/watch?v=y6t1woVd6RQ&t=537s

这是我的场景委托代码。

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        let launchedBefore = UserDefaults.standard.bool(forKey: "hasLaunched")
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let launchStoryboard = UIStoryboard(name: "Onboarding", bundle: nil)
        let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
        var vc: UIViewController
        if launchedBefore
        {
            vc = mainStoryboard.instantiateInitialViewController()!
        }
        else
        {
            vc = launchStoryboard.instantiateViewController(identifier: "Onboarding")
        }
        UserDefaults.standard.set(true, forKey: "hasLaunched")
        self.window?.rootViewController = vc
        self.window?.makeKeyAndVisible()

    //    guard let _ = (scene as? UIWindowScene) else { return }
    }

我已经尝试过注释掉最后一个警卫声明和不注释掉它。

4

2 回答 2

2

这是由马特解决的,请参阅他的答案。

只需在下面为任何尝试在 ios13 中使用情节提要进行入职培训的人发布正确的代码。

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        let launchedBefore = UserDefaults.standard.bool(forKey: "hasLaunched")
        let launchStoryboard = UIStoryboard(name: "Onboarding", bundle: nil)
        let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
        var vc: UIViewController
        if launchedBefore
        {
            vc = mainStoryboard.instantiateInitialViewController()!
        }
        else
        {
            vc = launchStoryboard.instantiateViewController(identifier: "OnboardingScene")
        }
        UserDefaults.standard.set(true, forKey: "hasLaunched")
        self.window?.rootViewController = vc
    }
于 2020-03-07T18:22:19.167 回答
2

您创建的窗口不正确,因此最终会出现黑屏。让情节提要为您创建窗口会更好,因为您不知道该怎么做。完全删除这一行:

self.window = UIWindow(frame: UIScreen.main.bounds)

你也可以剪掉这条线,因为它也是多余的(故事板也会为你做这件事):

self.window?.makeKeyAndVisible()

您现在唯一的责任是设置self.window?.rootViewController. 注意你不需要说

vc = mainStoryboard.instantiateInitialViewController()!

因为那已经是故事板给你的根视图控制器了。因此,在您提出的架构中,您唯一需要做的就是在用户需要登录的情况下替换根视图控制器。

(有关工作示例,请参阅我的 github 存储库。)

于 2020-03-07T18:14:13.573 回答