Unwind Segue from Navigation Back Button in Swift

Unwind segue function with Back button

You can use a delegate method to accomplish what you are doing.

Here is a really thought out swift tutorial that deal with delegates and segues:
http://makeapppie.com/2014/07/05/using-delegates-and-segues-part-2-the-pizza-demo-app/

What you are asking, ability to catch the back button's action, isn't possible the way you describe it.

Most people would recommend creating a custom button, then use an unwind segue.

There are lots of tutorials on custom back buttons just in case you're new to swift, and the ugly part of the custom back button can be easily fixed by putting your own arrow there.

Also I found this previous asked question for future reference: Unwind segue from navigation back button in Swift

unwind two segues from back button in swift


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.

Unwind segue with Navigation back button

In the end I didn't need to unwind the segue since I could still get a reference to the parent controller methods by following the navigation controller.

I was able to get a reference by doing the following in the - (void)viewWillDisappear:(BOOL)animated method of the child controller

NSInteger currentVCIndex = [self.navigationController.viewControllers indexOfObject:self.navigationController.topViewController];

FirstViewController *parent = (FirstViewController *)[self.navigationController.viewControllers objectAtIndex:currentVCIndex];

parent.barcodeType = indexPath.row;

which passed the settings variable back to the original controller perfectly.

I also added an import reference to the parent controller at the top of the childcontroller



Related Topics



Leave a reply



Submit