I have two view controllers. I have navigated from one view to another view by press the button to using below code.
*let secondViewController = self.storyb
To check whether the navigation stack contains a particular type of view controller
, you can use:
if let viewControllers = self.navigationController?.viewControllers
{
if viewControllers.contains(where: {
return $0 is YourViewController
})
{
//Write your code here
}
}
To remove a particular controller from navigation stack, you need to make changes to the navigation stack.
Example:
if var viewControllers = self.navigationController?.viewControllers
{
for controller in viewControllers
{
if controller is UIViewController
{
viewControllers.removeElement(controller)
self.navigationController?.viewControllers = viewControllers
}
}
}
Here we go.
This line will give you a array of UIViewControllers
self.navigationController?.viewControllers
Now what you have to do is check your viewControllerObject does exist or not?
By writing this line
if viewController.isKindOfClass(YourController){
}
and here is a complete code.
if let viewControllers = self.navigationController?.viewControllers {
for viewController in viewControllers {
if viewController.isKindOfClass(YourController) {
print("Your controller exist")
}
}
}
When you write below line while going back to your 'ViewControllerA' it will remove a ViewControllerB from navigation stack.
self.navigationController?.popViewControllerAnimated(true)
It is just similar pop operation which we are doing with stack and navigationcontroller is a stack.
Let me know if you have any confusions.
Here's another solotion:
guard let controllersInStack = navigationController?.viewControllers else { return }
if let yourViewController = controllersInStack.first(where: { $0 is YourViewController }) {
// Do what you want with yourViewController
}
All you need is to check with nibName of the viewController and you have your result
this code below will make sure you don't add one viewController again in navigatoinController,
var VC = YourViewController
var objVC = (storyboard.instantiateViewController(withIdentifier: "YourViewController"))
if navigationController.viewControllers.contains(where: { (VC) -> Bool in
return objVC.nibName == VC.nibName
}){
for (i,controller) in navigationController.viewControllers.enumerated()
{
if controller.isKind(of: VC){
navigationController.viewControllers.remove(at: i)
navigationController.pushViewController(objVC, animated: false)
}
}
}else{navigationController.pushViewController(objVC, animated: false)}
and If you just want to check if the viewController is in NaviagtionController then try this:
var checkForView = navigationController.viewControllers.contains(where: { (VC) -> Bool in
return objVC.nibName == VC.nibName
})