What is Unwind Segues?
An unwind segue is also called exit segue. By using unwind segue we can navigate backward from one screen to another screen. By Unwind segue we can navigate back through multiple screens with one action.
For Implementation of unwind segue follow these steps:
1. Set Storyboard like this. Three view controllers with the navigation controller.
Let’s take three view controllers — screen 1, screen 2 and 3.
We create a show segue from screen 1 to screen 2 and Present modally segue from screen 2 to screen 3. Now we can navigate forward by performing these segue. But for Backward navigation, we have to implement an unwind segue. It is very simple.
2. For this implement below action in Destination View Controller where we have to go from Third Screen. In Our Case write it in FirstVC.
@IBAction func unwindToFirstVC(segue:UIStoryboardSegue) { }
3. Now we can define an unwind segue in a storyboard.
For this , in storyboard control – drag and drop on exit icon like this.
In Presented options, select method that we implemented in First View Controller for unwind segue.
4. Now take a look at Document Outline of Third VC. In that ,from bottom select an unwind segue and in the attribute, inspector gives identifier to it like this.
5. Now in the last step write this code for performing an unwind segue in View Controller from where we want to perform it. In our example in ThirdVC.
@IBAction func btnGoToFirstVCTapped(_ sender: UIButton) { performSegue(withIdentifier: "unwindSegueTo1", sender: nil) }
Data Passing with Unwind Segue.
For example, if we want to pass a data from ThirdVC to FirstVC then what we will do? If we want to pass a name from ThirdVC and display it in FirstVC ?
Then in unwind, an action of FirstVC write this code.
@IBAction func unwindToFirstVC(segue: UIStoryboardSegue) { let vc = segue.source as! ThirdVC label.text = " Welcome \(vc.txtField.text!) " }
Conclusion
By following this steps we can easily pass data to previous controller without using protocol.