swiftuinavigationcontrollerviewcontroller

push VC while dismissing previous two presented VCs


I have VC1 that is in navigation controller, we are presented VC2 from VC1, then VC3 from VC2. When I click button in VC3, I need to dismiss VC2 and VC3, after which push VC4 to the VC1

So this VC1 (presented modally)-> VC2 (presented modally)-> VC3 to this VC1 (pushed to navigation controller)-> VC4

I tried everything but nothing works


Solution

  • The first is the method of closing vc2 when vc1 -> vc2 and entering vc3 from vc1. The second is a method that goes the way you want. Do you want to run it?

    extension UIViewController {
        
        func popAndPushViewController(goto: UIViewController) {
            if var vcArray = self.navigationController?.viewControllers {
                vcArray.removeLast()
                vcArray.append(goto)
                self.navigationController?.setViewControllers(vcArray, animated: true)
            }
        }
    
    
        func doublePopAndPushViewController(goto: UIViewController) {
            if var vcArray = self.navigationController?.viewControllers {
                vcArray.removeLast()
                vcArray.removeLast()
                vcArray.append(goto)
                self.navigationController?.setViewControllers(vcArray, animated: true)
            }
        }
    
    }
    
    let nextViewController = UIViewController()
    self.doublePopAndPushViewController(goto: nextViewController)