Search code examples
iosswiftmemory-leaksuinavigationcontrollerviewcontroller

How to pop the previous view controller from a navigation stack?


I use the navigation controller to push from view to view, but I don't pop any of the views that I push. So as I load a view I would like to pop the previous one from the stack.

Code for pushing views:

var identities = [String]()

identities = ["A", "B", "C", "D", "E"]

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

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

}

Test code for popping views (not what I want tho):

self.navigationController?.viewControllers.remove(at: 0)

Any help would be greatly appreciated.

Solved:

@DonMag helped walk me through the proper use and placement of that line of code.


Solution

  • It's really much simpler:

    self.navigationController?.popViewController(animated: true)