3

I am writing an IOS app in Swift.

After navigating to VC, I need to remove all view controllers except current (onscreen) from navigation controller. I am using below code and its working fine. But, it doesn't look optimized solution. Any better solution like syntactic sugar like map, filter, etc:

 if let nc = appDelegate().baseNavigationController{
   nc.viewControllers = Array(nc.viewControllers.dropLast(nc.viewControllers.count-1)
 }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Sheikh Atif
  • 139
  • 2
  • 12

3 Answers3

8

Instead of dropping and all, you can just use:

self.navigationController?.viewControllers = [self]
Jarvis The Avenger
  • 2,750
  • 1
  • 19
  • 37
  • Self is your current view controller – Jarvis The Avenger Jan 18 '19 at 12:12
  • 1
    @Sheikh Atif This comes with some problem of navigation. if there is a Back button in your view controller. you won't be able to GO BACK. – Jarvis The Avenger Jan 18 '19 at 12:14
  • yes, it worked well, and yes the current page is my authentication landing page, no back button. thanks – Sheikh Atif Jan 18 '19 at 12:15
  • 1
    @JarvisTheAvenger, I printed navigationController?.viewcontrollers after this statement and I saw that the previous vc was still in the stack. Any idea why it would still be present there? – Saad Rehman Dec 22 '20 at 10:43
  • @SaadRehman Can you please share the navigation structure of your app? check if you are not using multiple navigations in the app – Jarvis The Avenger Dec 23 '20 at 07:21
  • @JarvisTheAvenger I'm having the same problem that Saad is having when printing the navigationController?.viewcontrollers. Personally I have several storyboards leading up to the page where I need to empty the stack and some of them have navigation controllers of their own... knowing this, is there anyway to deal with this? – AlexT Oct 17 '22 at 06:42
2

In the viewDidLoad of your view controller set the viewControllers property of your navigation controller to the value you want, like this:

override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationController?.viewControllers = [self]
}
Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36
  • Awesome! nc.viewControllers = [AppStoryboard.Main.viewController(viewControllerClass: AuthenticationLandingViewController.self)] – Sheikh Atif Jan 18 '19 at 12:14
2

You can also remove it by getting the number of view controllers you have and removing them all except the last

if let viewControllerCount = self.navigationController?.viewControllers.count {
    self.navigationController?.viewControllers.removeFirst(viewControllerCount - 1)
}

If you have 5 view controllers, you would call removeFirst(5-1) so it can remove the first 4 view controllers.

codeherk
  • 1,609
  • 15
  • 24