swiftuinavigationcontrollerunwind-segue

Unwind to a specific view controller without a segue


When not using storyboards, how do you get the same functionality as an unwind segue? Say that I have a navigation controller with several view controllers in it, and I want to smoothly unwind back to a certain controller. How would you accomplish this?


Solution

  • You can write an extension on the UINavigationController to achieve this. As per your comments, you want to set an identifier and go back using that particular identifier. For that purpose, you can write a simple protocol:

    protocol Unwindable {
        var identifier: String { get set }
    }
    

    All your view controllers should confirm this protocol and set the identifier value. Implement the UINavigationController extension like:

    extension UINavigationController {
    
        func goBackToInstance(withIdentifier identifier: String) {
            let mapped = self.viewControllers.compactMap{ $0 as? Unwindable }
            for vc in mapped.reversed() {
                if (vc.identifier == identifier) {
                    self.popToViewController(vc as! UIViewController, animated: true)
                }
            }
        }
    }
    

    You can then go back using:

    self.navigationController?.goBackToInstance(withIdentifier: "Your Identifier")