[英]Change root view controller and dismiss all view controllers
I have an application in which if I already have a user's facebookUID
saved, I present them with the MainViewController
and set it as the rootViewController
, and if not, I present them with the LoginViewController
as the rootViewController
in my AppDelegate.swift
file. 我有一个应用程序,如果我已经保存了用户的
facebookUID
,我rootViewController
他们提供MainViewController
并将其设置为rootViewController
;如果没有,我将在我的AppDelegate.swift
文件中向他们提供LoginViewController
作为rootViewController
。
Inside the MainViewController
, there is a SettingsViewController
screen that I present modally. 在
MainViewController
内部,有一个我以模态显示的SettingsViewController
屏幕。 Inside that settings screen I have a logout button. 在该设置屏幕中,我有一个注销按钮。
My question is, how can set the rootViewController
as the LoginViewController
, and dismiss all the other controllers in the stack when they click the logout button? 我的问题是,如何将
rootViewController
设置为LoginViewController
,并在单击注销按钮时关闭堆栈中的所有其他控制器?
You do it, in essence, exactly the same way you do it in the app delegate. 本质上,您执行此操作的方式与在应用程序委托中完全相同。 But you are not in the app delegate, so you have to get there in steps:
但是您不在应用程序委托中,因此您必须按步骤进行操作:
From the UIApplication class you can get a reference to the shared
application object. 从UIApplication类,您可以获取对
shared
应用程序对象的引用。
From there you can get the app's delegate
. 从那里可以获取应用程序的
delegate
。
From there you can get the app delegate's window
. 从那里可以获取应用程序委托的
window
。
Now you can set the window's rootViewController
. 现在,您可以设置窗口的
rootViewController
。
The view controller that was the root view controller will vanish in a puff of smoke, along with all its dependent view controllers. 曾经是根视图控制器的视图控制器及其所有从属视图控制器将烟消云散。
(This, however, is not quite how I would do it. I would have a stable root view controller whose only job is to be custom parent view controller to either the LoginViewController or the MainViewController. I'm not fond of the idea of changing root view controller's in the middle of the app. Still, it's not illegal.) (但是,这并不是我的方法。我会有一个稳定的根视图控制器,其唯一的工作就是将自己的父视图控制器定制为LoginViewController或MainViewController。我不喜欢更改的想法根视图控制器位于应用程序的中间。但这仍然不是非法的。)
Try this code. 试试这个代码。 You can switch to Login screen with animation.
您可以切换到带有动画的登录屏幕。 Also no risk of retaining the old viewcontrollers hierarchy
也没有保留旧的ViewControllers层次结构的风险
if let appWindow = UIApplication.shared.delegate?.window {
UIView.transition(with: appWindow!,
duration: 0.6,
options: UIViewAnimationOptions.transitionFlipFromRight,
animations: {
let loginVC = LoginVC.init(nibName: "LoginVC", bundle: nil)
appWindow?.rootViewController = loginVC
},
completion: nil)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.