How to Pass Data using Segue and Unwind in Swift

Shankar Madeshvaran
Developer in Making
6 min readJun 10, 2019
Photo by Raagesh C on Unsplash
  • Segues are used to define the flow of your app’s interface. A segue defines a transition between two view controllers in your app’s storyboard file. The starting point of a segue is the button, table row, or gesture recognizer that initiates the segue. The end point of a segue is the view controller you want to display. A segue always presents a new view controller, but you can also use an unwind segue to dismiss a view controller.
  • You do not need to trigger segues programmatically. At runtime, UIKit loads the segues associated with a view controller and connects them to the corresponding elements. When the user interacts with the element, UIKit loads the appropriate view controller, notifies your app that the segue is about to occur, and executes the transition. You can use the notifications sent by UIKit to pass data to the new view controller or prevent the segue from happening altogether.

Output:

Segue and unwind operation

Let’s create a new Xcode project in File -> New -> Project -> ProjectName(eg: SegueTutorial) -> Next -> Create

1. Storyboard Designing

First, let’s create two viewcontrollers and name them LandingPageController.swift and FirstViewController.swift respectively.

Design the both viewControllers in AutoLayout and set the necessary constraints.

LandingPageViewController.Swift in Main.storyboard

LandingPageViewController’s Outlets:

  • UITextField — textField to get firstname of user
  • UIButton — button to push segue to FirstViewController.swift
  • UILabel — label to display fullname.
FirstViewController.swift in Main.storyboard

FirstViewController’s Outlets:

  • UITextField — textField to get lastname of user
  • UIButton — button to unwind segue to LandingPageViewController.swift
  • UILabel — label to display Firstname which is received from LandingPageViewController.

2. Embed NavigationController

Now, select the viewcontroller which need to embed navigationController.

Go to Edit -> Embed In -> NavigationController

NavigationController is Embed to LandingPageViewController in Storyboard

After embeding in the Navigation Controller set the navigationController as a initialViewController in Attributes Inspector by checking the isInitialViewController Checkbox.

Selecting NavigationController as a Initial View Controller in Attributes Inspector

3. Pass Data using Seque

After outlet is connected to respective viewController, select Enter Last Name button and then CTRL + Drag to NextViewController(i.e, FirstViewController) for showing the viewController from LandingPageViewController.

After CTRL + Drag the Enter last name button from LandingPageViewController to show FirstViewController

This lets you set what kind of segue you want to use. I would recommend sticking with those in the “Action Segue” section. They are new in iOS 8, and work better with the new Adaptive Layout than the deprecated ones below. What do each of these mean?

  • Show — When the View Controllers are in a UINavigationController, this pushes the next View Controller onto the navigation stack. This allows the user to click the back button to return to the previous screen through the back button on the top left of the Navigation Bar. Basically the adaptive form of “push”
  • Show detail — When the View Controllers are in a UISplitViewController, this will replace the detail view side of the UISplitView with the next View Controller.
  • Present modally — This presents the next view controller in a modal fashion over the current View Controller. This one doesn’t need to be part of a UINavigationController or a UISplitViewController. It just shows the destination View Controller in front of the previous one. This is usually used when the user has to either Finish or Cancel what they are doing, where leaving partway through doesn’t make as much sense. When you set up a new contact in the Contacts app, that is presented modally. Leaving partway through doesn’t make sense, you are either creating a new contact or you are not.
  • Popover presentation — On an iPad, this shows the new View Controller over the previous one in a smaller box, usually with an arrow pointing to which button created the popover. When used on an iPhone, it is not much different than the “Present Modally” segue by default, but can be configured to act more like an iPad one.
  • Custom — Exactly what it sounds like. You can make your own segue style and transitions and use it here. I have not dove into this yet, so I don’t know much more than that…. so far.

For now, We are going to use the “Show” segue.

LandingPageViewController.Swift

@IBOutlet weak var textFieldFirstName: UITextField!
@IBOutlet weak var labelFullname: UILabel!

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let firstVC = segue.destination as? FirstViewController else { return }
firstVC.firstname = textFieldFirstName.text
}

When a segue is triggered — perhaps through a button press or a table view selection — the prepare(for:) method will be called on your view controller, at which point you can configure your destination view controller by setting some properties.

When you tap the enter last name button, it will trigger the segue function and also show the FirstViewController.swift.You can also see the firstname data passing to the FirstViewController.

FirstViewController.Swift

@IBOutlet weak var textFieldLastName: UITextField!
@IBOutlet weak var labelFirstName: UILabel!

var firstname: String?

override func viewDidLoad() {
super.viewDidLoad()
labelFirstName.text = “Firstname: \(firstname ?? “”)”
}

After typing the firstname and tap enter last name button , first name value is passed to firstViewController and assigned to UILabel.

4. Implementation of unwind segue

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.

In FirstViewController.Swift, we are going to perform segue again to send last name to LandingPageViewController and also we are going to navigate from FirstViewController to LandingPageViewController using Unwind segue.

FirstViewController.Swift

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let LandingVC = segue.destination as? LandingPageViewController else { return }
if let firstname = firstname, let lastname = textFieldLastName.text {
LandingVC.fullname = firstname + “ “ + lastname
}
}

To perform Unwind segues:

To connect an unwind segue, you first need to mark the destination view controller with an unwind action.

Like other action methods, unwind actions are marked with the @IBAction keyword, but they get a UIStoryboardSegue as a parameter and not a sender.

  • UIStoryboardSegue — An object that prepares for and performs the visual transition between two view controllers.

Unfortunately, you can’t create an unwind action directly in a storyboard, as you would do for outlets and standard actions. You need to create the unwind action in code first and then make the connection in the storyboard.

LandingPageViewController.Swift

//To Perform Unwind Seque
@IBAction func performUnwindSegueOperation(_ sender: UIStoryboardSegue) {
guard let landingVC = sender.source as? LandingPageViewController else { return }
landingVC.fullname = textFieldFirstName.text
}

To Show FullName after perform Seque in LandingPageViewController.Swift

var fullname: String?

override func viewWillAppear(_ animated: Bool) {
guard let fullname = fullname else { return }
textFieldFirstName.text = “”
labelFullname.text = “Fullname: \(fullname)”
}

In FirstViewController connect to performUnwindSegueOperation(_ sender: Any) in storyboard to the ShowFullName button.

CTRL + Drag the ShowFullName button to Exit of FirstViewController to connect to performUnWindSegueOperation(_ sender: Any) Method.

Complete Code in LandingPageController.Swift File

Complete Code of LandingPageViewController.Swift File

Complete Code in FirstViewController.Swift File

Complete Code in FirstViewController.Swift File

5.Conclusion

This project is updated for Xcode 11 and Swift 5.0 .

Segues are a very important part of using Storyboards in Xcode. We can go over the different types of segues another time, but this one shows you how to use the “Show” segue, as well as how to pass data between the two view controllers to customize the second one with whatever custom data is required.

I hope you found this article helpful. If you did, please don’t hesitate to clap or share this post on Twitter or your social media of choice, every share helps me to write more. If you have any queries, feel free to comment below and I’ll see what I can do.Thanks.

Let’s connect!

You can find me on Twitter | LinkedIn | GitHub

--

--

Shankar Madeshvaran
Developer in Making

iOS and Web/React Js Developer. I write articles regarding Web, iOS ,React.Js concepts. Subscribe for more: https://shankarmadeshvaran.hashnode.dev