我正在尝试以编程方式更改我的应用的根ViewController。一旦用户注册我想要不同的根ViewController。这是我的代码
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "tabBarVC")
UIApplication.shared.keyWindow?.rootViewController = vc
UIApplication.shared.keyWindow?.makeKeyAndVisible()
self.present(vc, animated: true, completion: nil)
在呈现vc
之后我杀了应用程序,当我再次运行它时,根ViewControler是相同的。我究竟做错了什么?我也在AppDelegate中尝试了相同的代码,但没有成功。
答案 0 :(得分:0)
根据当前应用设置在appDelegate的didFinishLaunchingWithOptions
方法中设置此项,您也应使用window
而不是keyWindow
if(userExists)
{
let vc = storyboard.instantiateViewController(withIdentifier: "tabBarVC")
UIApplication.shared.window.first?.rootViewController = vc
}
else
{
let vc = storyboard.instantiateViewController(withIdentifier: "loginVC")
UIApplication.shared.window.first?.rootViewController = vc
}
不要使用礼物,因为这会自动更改根
另一种访问窗口的方法(在AppDelegate有值时使用)
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let homeController = mainStoryboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
appDelegate?.window?.rootViewController = homeController