Mark Meretzky
Mark Meretzky

Reputation: 99

Programmatically return to an earlier UIViewController in Swift

My iOS app (Xcode 11.5) has a view controller (an instance of class FirstViewController) that presents a UINavigationController. The UINavigationController pushes two view controllers (instances of classes SecondViewController and ThirdViewController). The ThirdViewController has a UIButton that successfully takes me back to the FirstViewController:

    @objc func buttonPressed(_ sender: UIButton) {
        assert(navigationController?.viewControllers.count == 2);
        performSegue(withIdentifier: "backToFirstViewController", sender: sender);
    }

I created this segue with the Interface Builder. Is there a way I could get back to the FirstViewController purely in Swift, without having to use a segue created with the Interface Builder? Thank you in advance.

Upvotes: 0

Views: 126

Answers (2)

luckystars
luckystars

Reputation: 1754

You could try something like this:

extension UINavigationController {

    func goBackTo<TargetViewController:UIViewController>(targetViewController:TargetViewController.Type) {
        let allViewController: [UIViewController] = self.viewControllers as [UIViewController]
        for aviewcontroller : UIViewController in allViewController {
            if aviewcontroller.isKind(of: targetViewController) {
                self.popToViewController(aviewcontroller, animated: true)
                break
            }
        }
    }
}

and you should be able to call it as :

   self.navigationController!.goBackTo(targetViewController: MyViewController.self)

Upvotes: 0

AdamPro13
AdamPro13

Reputation: 7400

You can do it programmatically without storyboards.

@objc func buttonPressed(_ sender: UIButton) {
     navigationController?.popToRootViewController(animated: true)
}

Upvotes: 0

Related Questions