Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check viewcontroller is added in stack or not

Tags:

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.storyboard!.instantiateViewControllerWithIdentifier("NotificationController") as! NotificationController  self.navigationController!.pushViewController(secondViewController, animated: true)* 

For the back, I am using bar button on bar button click for back using below code.

 self.navigationController?.popViewControllerAnimated(true) 

So my problem is if I am going from one view to another view continuously then it added in a stack. I want to only show another view when it is already added to the stack to stop adding it.It only adds one time.

like image 853
Gaurav Gupta Avatar asked Mar 16 '17 05:03

Gaurav Gupta


People also ask

How do I add a ViewController to a storyboard?

To create a new view controller, select File->New->File and select a Cocoa Touch Class. Choose whether to create it with Swift or Objective-C and inherit from UIViewController . Don't create it with a xib (a separate Interface Builder file), as you will most likely add it to an existing storyboard.

What is the difference between ViewController and UIViewController?

Both are used for different purpose. A UIViewController class manages a ViewContoller which is responsible for actions that happen within that View controller. This class is aware of actions that happen on view controller, like ViewDidLoad, ViewWillApper, ViewDidAppear, ViewWillDisapper, ViewDidDisapper.


2 Answers

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             }         }     } 
like image 85
PGDev Avatar answered Nov 18 '22 11:11

PGDev


For swift 4 you can use

 if let viewControllers = self.navigationController?.viewControllers {        for vc in viewControllers {             if vc.isKind(of: YourViewController.classForCoder()) {                  print("It is in stack")                  //Your Process             }        }  } 
like image 42
vp2698 Avatar answered Nov 18 '22 12:11

vp2698