Michael R
Michael R

Reputation: 93

Back Button Takes Me To Wrong View Controller

I have a storyboard I'm working with that is setup as so:

Login Screen -> Tab Bar Controller - > Navigation Controller - > Screen 1 Segue to Screen 2 Segue to Screen 3.

The first time I login, everything works great. Screen 1 segues to screen 2, screen 2 segues to screen 3, you can then use the back button to go back to screen 2 and then screen 1. However, I have a "logout" function (code below, although I don't think this is relevant to my issue) and after I "logout", it takes me to the Login Screen (first screen in the sequence above). When I then login again, navigate to Screen 2 or Screen 3, pressing the back button from the segue takes me all the way back to the login screen as opposed to the prior Screen 1 or Screen 2.

@objc func logOut(){
    let homeView = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
    self.navigationController?.pushViewController(homeView, animated: true)
    homeView.navigationItem.hidesBackButton = true
}

Upvotes: 1

Views: 121

Answers (2)

Michael R
Michael R

Reputation: 93

Updated for anyone who is curious. The pushViewController option was the issue. If i just use "present", I no longer have this issue. Here is my updated logout code:

@objc func logOut(){
    let homeView = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
    self.navigationController?.present(homeView, animated: true)
    homeView.navigationItem.hidesBackButton = true

}

Upvotes: 0

Slavenko Miljic
Slavenko Miljic

Reputation: 3856

I'm not sure that instantiating the LoginViewController again is the best practice, since you already have it in you navigation stack. I would recommend doing something like this:

@objc func logOut(){
    self.navigationController?.popToRootViewControllerAnimated(true)
}

This will remove all the view controllers from the navigtion stack, and present you with a root view controller (LoginViewController)

Upvotes: 1

Related Questions