PiterPan PiterPan - 1 year ago 298
Swift Question

How to create Unwind segue programmatically

I make an application using no storyboard and in this part of my app I need to create a unwind segue from

programmatically only. I know how to do it using sotorybard but can't find any solution how to do it programmatically. Any sugestions?

Answer Source

You can't create an actual segue without a Storyboard, but you can do the equivalent action by calling popToViewController on navigationController. Here is an example that is connected to a button to return to FirstViewController from ThirdViewController:

@IBAction func goBackToFirstVC(sender: UIButton) {
    guard let controllers = navigationController?.viewControllers else { return }
    let count = controllers.count
    if count > 2 {
        // Third from the last is the viewController we want
        if let firstVC = controllers[count - 3] as? FirstViewController {
            // pass back some data
            firstVC.someProperty = someData
            firstVC.someOtherProperty = moreData

            navigationController?.popToViewController(firstVC, animated: true)

In an override of viewWillAppear, you can act upon that data that was passed back.