Make App Pie

Training for Developers and Artists

Segue Actions

If you’ve been working with View controllers for a while, you’ve probably dealt with prepareForSegue. In Xcode 11, there’s a new way to handle this that makes a little more sense: Segue actions. Let’s take a look at this feature.  

If you download the storyboard, you’ll find I set one up for you. It is just a button that increments a counter on a detail view. Delete the segue between the two. I’ll use the button as navigation only. I’ll control-drag to the detail controller, and use a show segue. 

Open up the assistant editor. Control drag from the segue to the code for ViewController somewhere below viewDidLoad. Release the button. You’ll be asked for a connection. Name it addOneSegue. This method is a segue action, which triggers on a segue. It does much of what prepareForSegue does without some of the overhead. Add the action, and close up the assistant editor. Head over to the View Controller code. 

I’m going to make a counter. I’ll need a counter property here

var count = 1 

You’ll be more specific here than in a prepareForSegue. You make an instance of the controller, set its properties, and return the controller. No messing with id’s or anything else. Let’s try this.

   @IBSegueAction func addOneSegue(_ coder: NSCoder) -> DetailViewController? {

First, I’ll make an instance. Because this is instantiating to coder, this is optional. So use an if let here. 

    if let detailVC = DetailViewController( coder: coder){

If the controller instantiates, I’ll add one and set that in the detail. 

count += 1
detailVC.count = self.count

Then return the view controller.

return detailVC    

 And finally, if it doesn’t work, return nil.     

return nil

Over at the detail, we’re all set up with viewDidLoad updating the count. Run this.

You’ll get the button. Tap it. You get a count. Hit Back, then the button. Again, it updates. 

Segue actions save time in finding and naming segues and destination controllers. This new feature is a small gift of SwfitUI to UIKit. You’ll use this to get SwiftUI into storyboards, but I’ll discuss that at another time and in my Course SwiftUI Essential Training. Do remember outlet actions instantiate the instance, but do not load it. You still can’t assign a value to the label directly. 

I find this a better alternative than prepare for segue in delegation between my view controllers. 

The Whole Code

You can find the code for this lesson in GitHub here:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: