I have 4 view controllers suppose A,B,C,D. ViewController D is on top and on click of button I have to go to ViewController A and remove all remaining ViewControllers. How to achieve this
Asked
Active
Viewed 3,037 times
2
-
Are you using a navigation controller or added a child controller? – Harshal Valanda May 26 '17 at 09:26
-
Please provide more information... what is this "stack"? – Alladinian May 26 '17 at 09:27
-
If I understood correctly, something like [self.navigationController popToRootViewControllerAnimated:YES]; should work! – Vamshi Krishna May 26 '17 at 09:27
-
For swift 5, check this out https://stackoverflow.com/a/57327328/10579134 – Kedar Sukerkar Aug 02 '19 at 19:43
3 Answers
3
The UINavigationController's viewControllers property is get set property, that means you could write your own array of view controllers.
example,
let VCs = self.navigationController.viewControllers //VCs = [A, B, C, D]
let vcA = VCs[0] //vcA = A
//finally
self.navigationController.viewControllers = [vcA] //done
// OR
self.navigationController.setViewControllers([vcA], animated: true)
Shubham Naik
- 410
- 1
- 7
- 18
0
If you are looking for one viewController in the stack. I have also added the code for if you couldn't find that one controller in the stack goto mainController or the firstController in the stack:
if let viewControllers = self.navigationController?.viewControllers {
var element_count = 0
for controller in viewControllers {
if controller is YourViewController {
element_count = 1
self.navigationController?.popToViewController(controller, animated: true)
break
}
}
if element_count != 1{
_ = self.navigationController?.popToRootViewController(animated: true)
}
}
Prateekro
- 566
- 1
- 6
- 28