3

I have a tabBarController with four tabs. From each tab, I can navigate through a series of view controllers. And at the last view controller, I have a 'Done' button, clicking on which I have to be redirected to my initial tabBarController. The code I am using currently to do this is as follows (on button click).

let storyboard = UIStoryboard.init(name: "Main", bundle: Bundle.main)
if let tabViewController = storyboard.instantiateViewController(withIdentifier: "TabBarController") as? UITabBarController {
    self.navigationController!.pushViewController(tabViewController, animated: false)
}

But I feel this is not correct way since the navigation stack keeps on adding. Instead I would like to clear the navigation stack and show the first tabBarController in the stack. How can I solve this?

Kushal Shrestha
  • 775
  • 1
  • 10
  • 21
  • 2
    Possible duplicate of [Pop to root view controller from modal](https://stackoverflow.com/questions/39830955/pop-to-root-view-controller-from-modal) – AbecedarioPoint May 28 '18 at 09:58
  • Use the popToRootViewController(animated:) method on your navigationController. This makes sure that all the viewcontrollers in the array of view controllers are popped. https://developer.apple.com/documentation/uikit/uinavigationcontroller/1621855-poptorootviewcontroller – Milander May 28 '18 at 11:11

3 Answers3

6

make your first viewController your root view controller then on button click

self.navigationController?.popToRootViewController(animated: true)
Abhay Singh
  • 255
  • 1
  • 8
  • I also have splash screen as First viewController, if user go through login process then root viewcontroller will be splash view controller and after login tabbar controller will be display. – Kushal Shrestha May 28 '18 at 10:06
  • you can change your root view controller after login – Abhay Singh May 28 '18 at 13:04
2

I think setting root controller will solve your problem.

if let window = UIApplication.shared.keyWindow {
   let tabVC = UINavigationController(rootViewController: tabViewController())
   window.rootViewController = tabVC
}
Manish Mahajan
  • 2,062
  • 1
  • 13
  • 19
0

Use available method >>

func popToRootViewController(animated: Bool) -> [UIViewController]?

This method clears the stack and places you at the root view controller please read the documentation for detail

https://developer.apple.com/documentation/uikit/uinavigationcontroller/1621855-poptorootviewcontroller?changes=_4

  • When you reach the root view controller you find yourself at one of the tabs of your tab bar controller. Then you can switch tabs. – amar singh May 28 '18 at 10:44