更改 rootViewController 时 UIWindow 导致黑屏

UIWindow results in a black screen when changing the rootViewController

我将从主要问题开始:我的问题不容易重现。

所以...在我的应用程序中,根据用户是否是第一次打开它,我正在更改根目录ViewController。

我是这样做的:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        if /* code to figure out if it's the first launch */ {

            let storyboard = UIStoryboard(name: "Onboarding", bundle: nil)
            let onboardingViewController = storyboard.instantiateInitialViewController()

            window?.rootViewController = onboardingViewController
        }

        return true
    }
}

这基本上很好用!由于我目前正在构建 Onboarding ViewController,因此我删除了 if,因此它始终会显示。这也能正常工作,但突然之间应用程序无法启动。屏幕保持黑色。然后我 运行 在另一台设备上使用完全相同的代码,它在那里工作。 顺便提一句。上面的代码是我的 AppDelegate 中的全部代码,如果 OnboardingVC 将所有内容都注释掉,问题仍然存在。

当查看我的应用程序的 UI-Debugger 时,它看起来也很奇怪: 通常 UIWindow 旁边会有一个箭头,表明它的根确实是我的 VC,但在我的情况下并非如此。

我不介意,只是从我的设备上删除该应用程序,然后重新安装它,但我有一个用户投诉我的另一个应用程序,该应用程序使用相同的逻辑,谁告诉我确切的问题。现在我基本上重现了这个问题,但不知道问题应该在哪里。

顺便说一句,我的应用正在使用故事板。

也许有人以前遇到过这个问题并且知道可能是什么问题。

编辑:

今天又遇到了这个问题...这里有一些更多的观察结果: 当我启动 ViewController 并输出它的视图时,它是不正确的。这不是故事板中真正设置的视图。这是一个随机的其他视图。 故事板是否有可能损坏?如果是这样……我该怎么办? 在我向主视图控制器视图添加一个随机子视图并再次 运行 之后,它再次工作......所以显然故事板不知何故被破坏了?

好吧...在开发过程中...好吧...但是对于一个应用程序来说,故事板突然损坏了...这真的很糟糕!!!!

以前有人遇到过这个问题吗?以及如何解决?

试试这个 在你的情况下 window 是零所以

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        window = UIWindow(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
        if /* code to figure out if it's the first launch */ {

            let storyboard = UIStoryboard(name: "Onboarding", bundle: nil)
            let onboardingViewController = storyboard.instantiateInitialViewController()

            window?.rootViewController = onboardingViewController
        }
        return true
    }
}

我终于找到问题了。无论出于何种原因,我显然将 Initial-View-Controller 的视图出口双重链接到子视图。所以它有两个视图 属性 的出口(这怎么可能?) 它在启动时随机选择一个或另一个.... 把眼光很敏锐的朋友看出问题了:)