Segues in Swift

Transition between views using the Storyboard?

Image for post
Image for post
Photo by Gregory Hayes on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

Prerequisites:

  • Be able to produce a “Hello, World!” iOS application (guide HERE)
  • Know something about commenting in Swift (guide HERE)

Terminology

Segue: defines a transition between two view controllers in your app’s storyboard file

Storyboard: A way to graphically lay out the UI in Xcode

UINavigationController: A container that stores view controllers in a stack

UIViewController: A view controller is an intermediary between the views it manages and the data of your app

Unwind Segue: A segue used to navigate through previous segue operations

View Controller: Sits between the view and the model, tying them together (usually using the delegate pattern)

Connecting View Controllers

Using the storyboard to connect a series of UIViewControllers together is a matter of dragging and dropping objects on the storyboard.

First the initial view controller is added to Navigation Controller

Image for post
Image for post

The following animated GIF shows a how three view controllers can be placed in a row, with a simple segue added between each one, set as a show segue which means that each view controller slides in.

Image for post
Image for post

I’ve named the segues moveToSecond and moveToThird between the first and second view controllers and the second and third view controllers (respectively).

Add buttons with actions

We need to add a button for each view controller (in order to write code to kick off the segue).

This is a relatively easy drag and drop operation (only the first button is shown here)

Image for post
Image for post

Moving Data: Pass Data Through a Segue

It is possible to pass data from one view controller to another using a segue.

Switching to the first view controller gives us the following, with the important part that is commented out (FirstViewController is the class related to the first view controller, as shown in the animated gif above), and the button action is expressed.

We are going to use this to segue and pass information from one view controller to another by using performSegue(withIdentifier: String, sender: Any?), tooling it up in the button action.

We update the action to call the segue moveToSecond (as named above). Now in this case we don’t need to know the sender, so this can be nil but we need to absolutely be sure that the segue string is correctly identified. We all know matching Strings is a bad idea, but to avoid it you can see the lovely written article I previously made.

But pressing on without String matching, we use prepare(for:sender:) to, well, prepare for the segue. The finished method looks something like the following (which is added to our first view controller):

Now this relies on us having a dataSent property in the view controller we are visiting.

So we can place this in the rather attractively named SecondViewController, although it is just a simple property placed within the view controller class.

How best to show these? I’ll go for an animated GIF.

Image for post
Image for post

Moving Data: Pass Data Back Through a Delegate

What if you want to move data back from the second view controller, we might want to pass data back to the first view controller. One way for this is to use delegation.

To do so, we set up a delegate

We then need to conform to the delegate from the FirstViewController, with which we just print out the message

now within SecondViewController we add in the delegate as a property, which I’ve then chosen to call during the func viewWillDisappear(_ animated: Bool) so whenever the view is replaced the message is sent

There’s a couple of things there, so here is an animated gif

Image for post
Image for post

Unwind Segue

The unwind segue gives us something rather more.

To traverse from First View Controller to Second View Controller to Third View Controller is a stepwise process. However, an unwind segue gives the ability to move from Third View Controller to First View Controller, skipping the Second View Controller entirely.

Image for post
Image for post

Step in the unwind segue!

In the FirstViewController there needs to be a func unwindToFirst(_ unwindSegue: UIStoryboardSegue) function that will run when the storyboard moves back to the FirstViewController.

The storyboard section of this by control — dragging from a button to the top-right hand button “exit”

Image for post
Image for post
Image for post
Image for post

So difficult to show! Here is the animated GIF

Image for post
Image for post

It is also possible to pass data through the segue in a similar fashion to that described above.

Create your own, custom Segue

One reason to create your own segue is to create a nice animation when a view is presented.

My animation? A Fade Out (representing our fading from life, love).

The segue we create is a Custom Segue (rather than the show segue above).

Image for post
Image for post

Within this Segue we Need to select the Class of the segue, and set an identifier. Here we call it customSegue.

Image for post
Image for post

This then uses a whole new file to cover the newMyCustomSegue class; I’ve rather creatively called this file MyCustomSegue.swift , that inherits from UIStoryboardSegue.

The segue’s action will be, well, performed in the perform function with is overridden. override func perform()

Let us take perform() step-by-step. To gain control over the transition we set MyCustomSegue to be the transitioningDelegate. At the top of the class there is a retained reference private var selfRetainer: MyCustomerSegue? = nil that is required as UIKit does not retain instances of UIStoryboardSegue so a strong reference is created to the same. The presentation style is set to .fullScreen to replace the original view controller.

The transitioningDelegate provides methods that work for the presentation and dismissal. We will introduce two classes, Presenter and Dismisser to deal with those, that they adopt UIViewControllerAnimatedTransitioning and NSObject.

The presenter is quite easy to write.

Here we have the Presenter meets the protocol having the functions func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval and func animateTransition(using transitionContext: UIViewControllerContextTransitioning).

The former of these is simply a time, 1.5 is a rather nice span of time for this fade animation.

The letter is the animation; so the fade will be for the presenting view controller from translucent to opaque (that is 0.0 to 1.0).

What is that? You want a Playground with everything included? I’ll give you that, then:

Better will be a whole Repo with the work on it. Ok, that’s at the bottom of this page.

Conclusion

Segues are not as easy as one might think, but they allow you animate the user’s journey through your App and push data around.

Who would not want that?

I hope this guide has given you a nudge in the right direction for this (albeit fun) way of transferring your user and their data around an App.

Extend your knowledge

  • Apple have created documentation for segues HERE

The Twitter contact:

Any questions? You can get in touch with me HERE

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store