0

I'm creating a unwind segue using storyboard, following the instruction here.

But what I want to do is to create that unwind segue programmatically using swift,

The reason behind this is I want to create a default unwind segue to all of my UIViewController.

Dylan
  • 1,121
  • 1
  • 13
  • 28
  • The problem is that there is no UIViewController code method that does what an unwind segue in the storyboard does. And writing your own would be very, very difficult. I've added that to my answer. See also my answer to https://stackoverflow.com/questions/62152164/unwind-without-storyboard. – matt Jun 16 '20 at 14:37

2 Answers2

1

You can’t. A segue is something in the storyboard. Your code (programmatically) cannot see into the storyboard and change it.

Instead, you can do programmatically what the unwind segue did, such as pop back to a certain view controller.

But the general problem of "returning" to a certain view controller no matter what that may involve (some combination of dismiss and pop, etc.) is a very difficult and common one. It is certainly extremely annoying that, although a storyboard unwind segue "knows" how to do that, there is no method that lets you do that in code. I can only suggest filing a bug report with Apple.

matt
  • 515,959
  • 87
  • 875
  • 1,141
0

If you mean to go back to the root view controller you can use popToRootViewControllerAnimated on navigationController like this:

navigationController?.popToRootViewController(animated: true)

Or if you wish to pop back to a particular view controller then use:

navigationController?.popToViewController(secondViewController, animated: true)
Frankenstein
  • 15,732
  • 4
  • 22
  • 47
  • no, I don't mean to go back to the root view controller, my expected output was to create a default unwind segue to the UIViewController so it can unwind to the specific viewcontroller even it's not inside the navigation controller – Dylan Jun 16 '20 at 13:50
  • As @matt has explained segue is storyboard related and if you wish to go back to controller within the navigation controller then I've added that method too. – Frankenstein Jun 16 '20 at 13:52