iosswiftuiviewcontrollerpoptoviewcontroller

How to popToViewController which is not initialised in Swift?


I am facing problem in which I have four view controller on Main Screen. If the User directly go to second view controller from Main VC. I am unable to navigate to the first VC using popToViewController, because in memory we have only the two ViewController which is Main VC and my second VC.

How to navigate to first VC which still not initialised?
The Code is as below :

var viewControllersArray : NSArray = self.navigationController!.viewControllers!
var count = viewControllersArray.count
var i = 0
for i ; i < count ; i++ {
    var obj = viewControllersArray.objectAtIndex(i) as! UIViewController
    if obj.isKindOfClass(ThirdVC) {
        self.navigationController?.popToViewController(obj as UIViewController, animated: true)
    }
}

Please suggest the solution. Thanks in advance.

Note : I am doing the instantiateViewControllerWithIdentifier but problem is that it navigate to my second VC which not accepted.


Solution

  • Use the below code . May help it.

    var loginController: LoginViewController = LoginViewController(nibName:   
    "LoginViewController", bundle: nil)
    var vcs: [AnyObject] = 
    NSMutableArray.arrayWithArray(self.navigationController.viewControllers)
    if vcs.containsObject(loginController) {
       self.navigationController.popToRootViewControllerAnimated(true)
       return
    }
    vcs.insertObject(loginController, atIndex: vcs.count() - 1)
    self.navigationController.setViewControllers(vcs, animated: false)
    self.navigationController.popViewControllerAnimated(true)
    

    If View controller is not added in navigation stack then first add it into navigation stack and then pop that view controller.