3

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.

2 Answers2

9

It's really much simpler:

self.navigationController?.popViewController(animated: true)
DonMag
  • 69,424
  • 5
  • 50
  • 86
1

This is what worked for me:

var navigationArray = self.navigationController?.viewControllers

navigationArray.remove(at: 0)

self.navigationController?.viewControllers = navigationArray
pableiros
  • 14,932
  • 12
  • 99
  • 105
  • I implemented this and it's real close to working. The only problem is with every time you push from the initial view controller (a small memory increase). Can't put this code there because it will just delete itself. All the other views seem to be fine. Any suggestions? – Slavic the Slavic Apr 27 '17 at 18:19