3

What I want is to close a viewController after performing a segue so that the back button of the navigation controller on the new view doesn't go back to the view that I just closed, but it goes to the view that precedes it in the storyboard like it is the first time that it is loaded.

enter image description here

I already tried stuff like dismiss and so but it doesn't really work for me as it only closes the view in which the button that I pressed for performing the function is located :

@objc func goToList(){
   self.dismiss(animated: true, completion: nil)
   performSegue(withIdentifier: "goToList", sender: nil)
}
Marina Aguilar
  • 1,151
  • 9
  • 26
Poli97
  • 305
  • 4
  • 18
  • I would recommend looking at the Apple documentation about the UINavigationController:(https://developer.apple.com/documentation/uikit/uinavigationcontroller) That should contain the answer to your question. I would specifically look at the 'topics' section and look into the documents about "pushing and popping stack items". It will be much more valuable if you're able to search through the documents for your answers! Trust me! – gavsta707 Oct 21 '19 at 15:30
  • I wasn't thinking of doing it in that way but anyway it worked, so thank you! – Poli97 Oct 21 '19 at 17:04

2 Answers2

3

The navigation controller maintains a stack (array) of ViewControllers that have been opened (pushed). It also has the ability to pop these ViewControllers off the stack until it gets to a specific one.

For example, if you wished to return to a previous view controller of type MyInitialVC then you'd want to search through the stack until you found that type of VC, and then pop to it:

let targetVC = navigationController?.viewControllers.first(where: {$0 is MyInitialVC})
if let targetVC = targetVC {
   navigationController?.popToViewController(targetVC, animated: true)
}

NB. written from memory without XCode, so you may need to correct minor typos

flanker
  • 3,840
  • 1
  • 12
  • 20
0

You can use unwind segue to get back to each viewController that you want.
Read more here:
Unwind Segues Step-by-Step (and 4 Reasons to Use Them)

Arash Etemad
  • 1,827
  • 1
  • 13
  • 29
  • Tried that too but don't know why when i control+drag the viewcontroller i am not able to link that to the Exit icon – Poli97 Oct 21 '19 at 16:52
  • You should ctrl+drag from viewController's icon at the top to exit icon if you want to call it programmatically otherwise you should ctrl+drag from the button that you want to exit! of course, all of this need that you should define your `unwind func` in the first viewController, not the last one! – Arash Etemad Oct 22 '19 at 05:27