Search code examples
iosswiftuinavigationcontrollerappdelegate

How can I present VC and set as new Root viewController in Swift?


I have this warning: Presenting view controllers on detached view controllers is discouraged

I need to know how can set my rootViewController in another VC and avoid this warning

I have this code in my VC:

@IBAction func dissmissInfo(_ sender: UIButton) {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "firstVC")
     present(vc, animated: true, completion: nil)
    })

And in the firstVC I have this:

    override func viewDidLoad() {
        super.viewDidLoad()

        UIApplication.shared.keyWindow?.rootViewController = self
}

but when I try to move to another VC I have the same warning: Presenting view controllers on detached view controllers is discouraged


Solution

  • You mean you want to set firstVC

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "firstVC")
    

    as the new RootViewController?

    If YES:

    @IBAction func dissmissInfo(_ sender: UIButton) {
         let storyboard = UIStoryboard(name: "Main", bundle: nil)
         let vc = storyboard.instantiateViewController(withIdentifier: "firstVC")
         UIApplication.shared.keyWindow?.rootViewController = vc 
    })
    

    Then in firstVC, remove

    UIApplication.shared.keyWindow?.rootViewController = self