如何在App Delegate中使控制器独立?

时间:2019-04-13 22:55:21

标签: swift

因此,在AppDelegate.swift文件中,我有一个UINavigationController作为根视图控制器,一个mainController作为navigationController的topViewController。我在这里实例化了所有数据,因此它可以是独立的。现在,我想将MenuController用作topViewController,但是我不确定如何从此处调用mainController。

更具体地说,我正在创建一个填字游戏,我一直专注于网格等的逻辑和实现。现在,我想在显示填字游戏之前将“菜单”作为我的第一个屏幕。

MainMenu-> MenuController
CrosswordGame-> MainController

这是我在AppDelegate.swift

中没有MainMenu实现的代码
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        // Create a ButtonStore
        let buttonStore = ButtonStore()
        let levelStore = LevelStore()

        // Access the MainController and set its buttonStore
        let navController = window!.rootViewController as! UINavigationController
        let mainController = navController.topViewController as! MainController
        mainController.buttonStore = buttonStore
        mainController.levelStore = levelStore
        return true
    }

这就是我现在拥有的

        // Create a ButtonStore
        let buttonStore = ButtonStore()
        let levelStore = LevelStore()

        // Access the MainController and set its buttonStore
        let navController = window!.rootViewController as! UINavigationController
        let menuController = navController.topViewController as! MenuController
        // Instantiate MainController and add buttonStore / levelStore to MainController


        return true

我只是不希望我的填字游戏在按Back键回到MainMenu时丢失其数据。另一个问题是,是否可以将其放入AppDelegate或在MenuController中实例化MainController。

1 个答案:

答案 0 :(得分:2)

    //create your view controllers and set any properties
    let game =  UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "mainControllerIdentifier")
    let menu =  UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "menuControllerIdentifier")

    //create the navigation controller
    let navigationController = UINavigationController()

    //set the content controllers on the nav controller
    navController.setViewControllers([game, menu], animated: false)

   //assign the navigation controller as the root controller of the window
    window.rootViewController = navigationController