richc richc - 7 months ago 66
Swift Question

unwind two segues from back button in swift

I have a parent view controller where a user selects the game they want to play, then a child 1 view controller where the game is played, then a child 2 view controller which shows scores once the game is completed. How do I use the standard back button in child 2 view to get back to the parent view controller. I don't need to pass anything between the child 2 VC and the parent.

I have created an unwind segue in the parentVC

@IBAction func unwindToParentVC(segue: UIStoryBoardSegue) {
}


And I have ctrl dragged from the yellow Child 2 VC icon onto the Exit icon and selected the above unwind segue, but I the back button doesn't seem to fire this segue.

I have read other solutions on SO that say I need to use

override func didMoveToParentViewController(parent: UIViewController?) {
}


But i am not sure how to get the back button to call this method, and what code I need to add in the body of the method. Any help on where I am going wrong much appreciated!

Answer

How do I use the standard back button in child 2 view to get back to the parent view controller.

The standard back button (in a UINavigationController) really only does one thing: pop the current view controller off the navigation stack, which returns to the previous view controller. Instead of trying to change that behavior, you can simply change which view controller is previous.

Custom segue example:

class ReplaceSegue: UIStoryboardSegue {
    override func perform() {
        guard let nav = sourceViewController.navigationController
            else { return }

        // Remove current view controller from navigation stack before segue
        let viewControllers = nav.viewControllers.filter { $0 != sourceViewController }

        // Add destination to view controllers and perform segue
        nav.setViewControllers(viewControllers + [destinationViewController], animated: true)
    }
}

Then update your segue class to ReplaceSegue between child 1 and child 2. This will remove child 1 from the navigation stack at the time of segue, such that when the user taps the standard back button on child 2, it returns to parent.