Kushal Shrestha
Kushal Shrestha

Reputation: 805

Clear Navigation stack of viewcontroller

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?

Upvotes: 3

Views: 7104

Answers (3)

amar singh
amar singh

Reputation: 1

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

Upvotes: 0

Manish Mahajan
Manish Mahajan

Reputation: 2082

I think setting root controller will solve your problem.

if let window = UIApplication.shared.keyWindow {
   let tabVC = UINavigationController(rootViewController: tabViewController())
   window.rootViewController = tabVC
}

Upvotes: 2

Abhay Singh
Abhay Singh

Reputation: 265

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

self.navigationController?.popToRootViewController(animated: true)

Upvotes: 6

Related Questions