2015-11-29 35 views
0

我有一個應用程序,它有一個LoginViewController和一個DashboardViewController。如果用戶成功登錄,他/她將被帶到DashboardViewController。將視圖控制器彈出到一個不存在的視圖控制器

LoginViewController有一個記住我選項。如果用戶在登錄時勾選它,那麼該值將存儲在NSUserDefaults中以用於後續登錄。例如,如果用戶在登錄時打開選項,則下次用戶打開該應用程序時,他/她將直接進入DashboardViewController,而不顯示LoginViewController。

這是我有的故事板結構。

enter image description here

在AppDelegate中,我根據所保存的值NSUserDefaults的設置窗口的RootViewController的。

if !NSUserDefaults.standardUserDefaults().boolForKey(Globals.IsLoggedIn) { 
    // Show login screen 
    let loginViewController = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()).instantiateViewControllerWithIdentifier("LoginViewController") 
    let navigationController = UINavigationController(rootViewController: loginViewController) 
    window?.rootViewController = navigationController 
} else { 
    // Show Dashboard 
    let dashboardViewController = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()).instantiateInitialViewController()! 
    let navigationController = UINavigationController(rootViewController: dashboardViewController) 
    window?.rootViewController = navigationController 
} 

這一切都很好。問題是我必須註銷。

在DashboardViewController的導航欄中,有一個UIBarButtonItem,可在您點擊並確認時將您註銷。

let alert = UIAlertController(title: "Logout", message: "Are you sure you want to logout?", preferredStyle: .Alert) 
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) 
alert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: { (action) -> Void in 
    NSUserDefaults.standardUserDefaults().setBool(false, forKey: Globals.IsLoggedIn) 
    self.navigationController?.popViewControllerAnimated(true) 
})) 
presentViewController(alert, animated: true, completion: nil) 

如果從LoginViewController用戶登錄,移動到DashboardViewController和註銷時,DashboardViewController彈出導航堆棧和LoginViewController出現。都好。

但是說我在上次登錄時打開了記住我選項,我打開了該應用程序。現在我直接進入DashboardViewController。注意嵌入DashboardViewController的navigationController如何設置爲窗口的rootViewController。

所以如果我現在註銷,LoginViewController沒有實例可以回彈,因爲它從來沒有添加過!

如何解決這種情況?有沒有辦法偷偷實例化一個LoginViewController實例,即使直接直接顯示DashboardViewController,但默默地將其添加到導航堆棧,但仍然顯示DashboardViewController作爲第一個視圖控制器或什麼?

或者你會推薦一個不同的方法,總體架構?

回答

1

試試這個:

let vc = self.storyboard?.instantiateViewControllerWithIdentifier("LoginViewController") 
self.navigationController?.viewControllers.insert(vc!, atIndex: 0) // at the beginning 
self.navigationController?.popViewControllerAnimated(true) 
+0

這是一個巧妙的方法。我[修改](http://pastie.org/10589772)我的代碼基於你的解決方案,它的作品完美。謝謝。 – Isuru

+0

是的,當你學習如何使用可用的工具時感覺很好。 –

相關問題