以编程方式设置为根视图控制器时,情节提要的视图控制器未显示

Storyboard's view controller not showing up when programmatically set as root view controller

我正在尝试根据应用程序启动时的某些条件更改根目录VC。我所有的 VC 都是在情节提要中制作的,所以我是这样做的:

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

                    checkPhotoLibraryAccess()

                    return true
                }

func checkPhotoLibraryAccess(){

                    if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.denied ||  PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.notDetermined {
                        showPermissionVC()
                    } else {
                        showContainerVC()
                    }
                }

func showPermissionVC (){

                    let storyboard = UIStoryboard(name: "Main", bundle: nil)

                    let rootVC = storyboard.instantiateViewController(withIdentifier: "askPermissionVC")

                    UIApplication.shared.windows.first?.rootViewController = rootVC

                    self.window?.makeKeyAndVisible()

                }

func showContainerVC (){

                    let storyboard = UIStoryboard(name: "Main", bundle: nil)

                    let rootVC = storyboard.instantiateViewController(withIdentifier: "containerVC")

                    UIApplication.shared.windows.first?.rootViewController = rootVC

                    self.window?.makeKeyAndVisible()

                }

我已经从故事板中删除了显示初始 VC 的箭头,这样它就不会与代码发生冲突。但是,我遇到了这个错误,模拟器的屏幕上什么也没有显示:

[Application] Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set?

我现在已经从 info.plist 中删除了 "Main storyboard file base name" 属性。这次错误消失了,但仍然没有任何显示。我做错了什么?

您需要以编程方式初始化 window。

尝试将以下内容添加到 Appdelegate

didFinishLaunchingWithOptions 方法的开头
self.window = UIWindow()

同样在您的 showPermissionVCshowContainerVC 方法中,替换此行:

UIApplication.shared.windows.first?.rootViewController = rootVC

与:

window?.rootViewController = rootVC