Leem.fin Leem.fin - 1 month ago 6
iOS Question

Go back to previous view controller doesn't work

My first view controller has a button, which triggers the @IBAction

goTo2ndVc()
which presents a second ViewController:

class FirstVC: UIViewController {
...
@IBAction func goTo2ndVc() {
let secondVc = SecondVC(label: "I am second vc.")
self.presentViewController(secondVc, animated: true, completion: nil)
}


When the button is pressed, the 2nd view controller is shown on screen. No problem.

In 2nd view controller, there is also a button which is used to go back to 1st view controller:

class SecondVC: UIViewController {
...
@IBAction func backToFirst(sender: AnyObject) {
print("go back ...")
self.navigationController?.popViewControllerAnimated(true)
}
}


I looked on internet, people suggest to use
navigationController?.popViewControllerAnimated(true)
to go back to previous controller. But when I press the go back button I can see the print message "go back ..." but the app doesn't go back to 1st view controller. WHY?

Answer
@IBAction func backToFirst(sender: AnyObject) {
    print("go back ...")
    self.dismissViewControllerAnimated(true, completion: nil)
}

you should not use navigation controller, because you didn't use it when you were adding the second view controller. that's why simply call dismissViewControllerAnimated method.

You have to use UINavigationController and its pop methods only when you add your view controllers via pushViewController method.

Familiarize yourself with the concept of navigation controller here: https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/ViewControllerCatalog/Chapters/NavigationControllers.html