我有一个应用程序,它有一个LoginViewController和一个DashboardViewController。如果用户成功登录,他/她将被带到DashboardViewController。将视图控制器弹出到一个不存在的视图控制器
LoginViewController有一个记住我选项。如果用户在登录时勾选它,那么该值将存储在NSUserDefaults中以用于后续登录。例如,如果用户在登录时打开选项,则下次用户打开该应用程序时,他/她将直接进入DashboardViewController,而不显示LoginViewController。
这是我有的故事板结构。
在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作为第一个视图控制器或什么?
或者你会推荐一个不同的方法,总体架构?
这是一个巧妙的方法。我[修改](http://pastie.org/10589772)我的代码基于你的解决方案,它的作品完美。谢谢。 – Isuru
是的,当你学习如何使用可用的工具时感觉很好。 –