Nifty Ways of Segueing and Passing Data Between View Controllers

There are several ways to segue and pass data between View Controllers. In part one of this series, we will focus on getting our First View Controller to pass its data to Second View Controller.

There are primarily three ways of accomplishing this:

Storyboard

Hybrid of Storyboard and Programmatically

Programmatically

Storyboard Only Approach

Arguably the simplest way to pass data is through storyboards. To start, hold the control key, click on a UI Control (a UIButton in our case), and drag to Second View Controller. The pop-up menu will display different types of transitions. Select ‘Show.’

This sets up a segue from your UI control to the Second View Controller. Now any time a user interacts with our button, your app will automatically transition to displaying Second View Controller.

Don’t forget to give our segue an identifier so we can refer to it in code. We will call ours showSecondViewController. Typically your first word should be a verb that helps describe what the segue accomplishes.

Now we will jump into First View Controller and write the following code:

Hybrid Approach

While the previous approach works, sometimes you want control over when the segue begins transitioning. In this scenario, the hybrid approach is a my tool of choice.

You start by setting up a segue by control clicking on the view controller icon instead of a UIControl. This is the yellow circle found at the top of First View Controller in storyboards.

Just as before, you also set the segue’s identifier so you can later pass data in prepare(for: segue)

All that remains is to call performSegue(withIdentifier: “showSecondViewController”, sender: self). This will begin the segue at a time of your choosing, and data will pass in prepare(for segue) just as before.

Programmatic Approach

It is important to understand just what storyboard segues are doing for us when we transition from one View Controller to the next. That way we will know what we must replicate in our code. It turns out it is not complicated:

Conclusion

Hybrid: Segue transitions only when you call performSegue(withIdentifier: sender:).Data passed in prepare(for: segue).

Programmatically: No segue created in storyboard.Call storyboard?.instantiateViewController(withIdentifier:) to create an instance of Second View Controller.Pass data manually and call present(viewControllerToPresent: animated: completion:) when you are ready to transition to Second View Controller.

Congratulations! As programmers it is always good to know multiple ways of accomplishing a task, and using the best one for any given scenario.