CodeDezk
CodeDezk

Reputation: 1260

ios swift cannot dismiss view controller

I am opening new viewcontroller like

            let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let view_controller1 = storyBoard.instantiateViewController(withIdentifier: "incident_view_id") as! IncidentViewController
            let appDelegate = UIApplication.shared.delegate as! AppDelegate
            //self.present(registerViewController, animated: true)
             let navigationController = UINavigationController.init(rootViewController: view_controller1)
            appDelegate.window?.rootViewController = navigationController

Which works fine,

Now when I press a button I need to close current view and go back previous view, I tired

self.navigationController?.popToRootViewController(animated: true)

But not works, I tried this too

self.view.window!.rootViewController?.dismiss(animated: true, completion: nil)

But same result.

Upvotes: 1

Views: 672

Answers (1)

πter
πter

Reputation: 2217

You are presenting your ViewController in a wrong way. The following line tells the application to no matter what ViewControllers you have opened, just throw it out and assign the UINavigationController what you are creating, as the rootViewController. So the reason your code, the dismiss, is not working because there are no other ViewControllers behind your current one.

appDelegate.window?.rootViewController = navigationController // Wrong 

This usually goes into the beginning of the applications, where you define with which UIViewController you want to start your application. I believe you are calling the first code chunk you posted from a UIViewController. So what you need to do instead of creating a new UINavigationController and assigning it to the rootViewController, you just use the UIViewControllers navigation controller to push the next UIViewController.

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let view_controller1 = storyBoard.instantiateViewController(withIdentifier: "incident_view_id") as! IncidentViewController
navigationController?.pushViewController(view_controller1, animated: true)

Upvotes: 2

Related Questions