Start a Project

Unwind Segue in Swift

The segue used to create a new view controller instance in swift. It works programmatically and in the storyboard, with Interface Builder, and once a segue gets triggered, it can’t go back. It is like a one-way direction.

The unwind segue allows to you jump from the one view controller to any view controller without the following hierarchy of view controller but proceed to the destination. Let’s assume you have n numbers of View Controller. You have already pushed or present from many controllers to other controllers. But now you want to return back from your controller but not the previous controller. Let’s suppose you are in the fifth pushed controller and from there you want to return directly in the second parent controller. Then there we can use unwind segue.

How the Unwind Segue Works.

Find the destination from the current view controller’s can be a parent or presenting view controller. 

In runtime, it always checks that the view controller has any children. There can be a segue method contained in one of those children.

It can be done by allowedChildrenForUnwinding(from:)  method which returns the array of children UIViewController.

It calls the childContaining(_:) method to run the first child view controller that contains the source view controller unwind segue.

If there are no children found then  canPerformUnwindSegueAction(_:from:sender:) method is called, which returns that view controller contains the unwind method.

If there is unwind method then it jumps from that view controller to the destination view controller.

Implementation of Unwind Segue

Let’s create a new Xcode project of unwind segues and open the project, implement as:

1.) Add three new view controllers to the storyboard. Also, add three swift files as UIViewController and name as FirstViewController, SecondViewController, and ThirdViewController.

2.) Embed the FirstViewController with a navigation controller.

3.) Add button to push the controller from one controller to another controller.

4.) Now push the controller from one controller to another controller with a unique identifier as:

Move from FirstViewConrtroller to SecondViewController:

Move from SecondViewConrtroller to ThirdViewController:

5.) Now add the unwind segue method at FirstViewController as:

6.) Now from the storyboard, select ThirdViewController and drag from the view controller to the Exit proxy and select the unwind method.

 

7.) Arrange the properties of  the unwind segue in the storyboard accordingly as:

8.) Now triggered the action in the ThirdViewController for the unwind segue method.

9.) Let’s run the project and it will work as:

Conclusion

I hope this tutorial will help you if you have any comments, questions, or recommendations, feel free to post them in the comment section below!

For other blogs, please click here.

Exit mobile version