Search code examples
iosswiftxcodecocoa-touchuinavigationcontroller

I have issue to remove ViewController from Navigation stack?


I have 5 VC's, I'm successfully removing ViewController from navigation stack. But the problem is when click back button on navigation, it's moving into previous VC and it's showing removed VC on navigation bar.

Ex: I have 5 VC's: VC1, VC2, VC3, VC4, VC5.

Now I'm navigating from VC1 -> VC2, ..... VC4 -> VC5. And I have custom navigation bar back button title. Here I'm removing VC4 from stack.

When click back button in VC5 it's directly moving into VC3. But navigation bar is VC4. When click navigation bar once again now it's displaying VC3 navigation bar in same VC.

HOW TO resolve this issue. I want to display directly VC3 and vc3 navigation bar in single click.

Code to remove VC from Navigation stack:

guard let navigationController = self.navigationController else { return }
var navigationArray = navigationController.viewControllers // To get all UIViewController stack as Array
navigationArray.remove(at: navigationArray.count - 2) // To remove previous UIViewController
self.navigationController?.viewControllers = navigationArray

Solution

  • Hide default back button and add custom back button with action:

    override func viewDidLoad {
        super.viewDidLoad()
        self.navigationItem.hidesBackButton = true
            let customBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItem.Style.plain, target: self, action: #selector(back))
            self.navigationItem.leftBarButtonItem = customBackButton
    }
    

    Use popToViewController to move back to specific viewcontroller:

    @objc func back(sender: UIBarButtonItem) {
        guard let navigationController = self.navigationController else { return }
    var navigationArray = navigationController.viewControllers // To get all 
    self.navigationController!.popToViewController(navigationArray[navigationArray.count - 2], animated: true)
    }