gpt4 book ai didi

ios - 弹出 View Controller 到一个不存在的 View Controller

转载 作者:行者123 更新时间:2023-11-29 01:26:11 26 4
gpt4 key购买 nike

我有一个应用程序,它有一个 LoginViewController 和一个 DashboardViewController。如果用户成功登录,他/她将被带到 DashboardViewController。

LoginViewController 有一个记住我选项。如果用户在登录时勾选它,该值将存储在 NSUserDefaults 中以供后续登录使用。例如,如果用户在登录时打开“记住我”选项,则下次用户打开应用程序时,他/她将直接进入 DashboardViewController,而不会显示 LoginViewController。

这是我的 Storyboard结构。

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 的实例,因为它从一开始就从未添加过!

如何解决这种情况?有没有办法 secret 实例化 LoginViewController 的实例,即使直接显示 DashboardViewController,但默默地将其添加到导航堆栈,但仍然将 DashboardViewController 显示为第一个 View Controller 或其他东西?

或者您会推荐一种不同的方法、整体架构吗?

最佳答案

试试这个:

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

关于ios - 弹出 View Controller 到一个不存在的 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33985343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com