以编程方式设置为根视图控制器时,不会显示Storyboard的视图控制器

时间:2019-03-25 17:16:39

标签: ios swift storyboard rootviewcontroller

我正在尝试根据应用启动时的某些情况来更改rootVC。我所有的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的箭头,以免与代码发生冲突。但是,我收到了此错误,模拟器中的任何内容均未显示在屏幕上:

  

[应用程序]无法实例化默认视图控制器以用于   UIMainStoryboardFile'Main'-也许指定的入口点是   没有设置?

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

1 个答案:

答案 0 :(得分:0)

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

尝试将以下内容添加到didFinishLaunchingWithOptions中的Appdelegate方法的开头

self.window = UIWindow()

还要在您的showPermissionVCshowContainerVC方法中,替换以下行:

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

具有:

window?.rootViewController = rootVC