我正在尝试以编程方式更改应用程序的根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中尝试了相同的代码,但没有成功。
didFinishLaunchingWithOptions
根据当前的应用设置在appDelegate的方法中进行设置,也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
}
不要使用present,因为这会自动更改根
也是访问窗口的另一种方法(在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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句