iosswiftuinavigationcontrollerpoptoviewcontroller

How to properly use popToViewController?


What I am trying to do, is to pop all previous view controllers from the stack up to the 'menu' controller. I have a piece of code that is supposed to do that, but when 'menu' is clicked, the app crashes.

The reason for the crash: 'Tried to pop to a view controller that doesn't exist.'

Here is part of my code:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    // 0 = menu
    if indexPath.row == 0 {
        let vcName = identities[indexPath.row]
        let viewController = storyboard?.instantiateViewController(withIdentifier: vcName)
        let _ = navigationController?.popToViewController(viewController!, animated: true)

    } else {

        let vcName = identities[indexPath.row]
        let viewController = storyboard?.instantiateViewController(withIdentifier: vcName)
        self.navigationController?.pushViewController(viewController!, animated: true)
    }
}

Solution

  • You can't instantiate a new instance of the view controller you are trying to pop to; you need to pop to the actual instance that is in the navigation stack.

    If your menu is the root of your navigation stack then you can use popToRootViewController. If it is somewhere else in the stack then you either need to hold a reference to it or you can iterate through the navigation controller's viewControllers array to find it and then pop to it.

    if let navController = self.navigationController {
        for controller in navController.viewControllers {
            if controller is MenuController { // Change to suit your menu view controller subclass
                navController.popToViewController(controller, animated:true)
                break
            }
        }
    }