Move between View Controllers with Segues — iOS #9

icons from icons8.com as usual, the legends

Creating new View Controllers (aka screens) in an app and moving between them is core to building apps. This post will show you the basics. We’ll:

  • Add a new View Controller to the storyboard
  • Add a new Swift file for that View Controller
  • Link the two
  • Add a Segue between two View Controllers
  • Create a Button that when clicked, will use the Segue to send the user to the second View Controller
  • Add a Button on the Second View Controller than when clicked, will close the View Controller and return the user to the first.
  • Send information from the first to the second and display it on a Label.

Let’s go! Open Xcode and create a new project. Head to the Main.storyboard and from the Object Library drag out a View Controller onto the Storyboard:

If you remember, there’s two pieces to every “screen” in an app — a View Controller object (which we just added to the Storyboard) and also a corresponding Swift code file which is linked to the View Controller.

By default, when you create a new app, the default View Controller comes automatically with a linked Swift file — but for every new View Controller you add, you need to manually add and link a new Swift file. Let’s do that now.

In the Project Explorer on the left-hand panel, right-click on the root folder and select New File:

On the next dialog box, make sure Cocoa Touch Class is selected and hit Next:

In the next box, give it any name you want in the Class field; here I use “SecondViewController” … as it’s going to be our … second View Controller. But I could have called it “MyAmazingViewController” or “MickeyMouse” or whatever.

Ensure the Subclass field is set to UIViewController, this is essential. Hit Next when you’re ready.

On the next screen, just hit Create (unless you want to change where the file will be stored for some crazy reason!):

and you should see a new file created:

Great. Now we need to link this to the View Controller we dragged out earlier onto the Storyboard. Head back there and click on the little button at the top of the View Controller:

Now hit the third icon on the right-hand panel to open the Identity Inspector:

In the Class field, enter the name of your newly created Swift file and hit Enter on the keyboard i.e.

The View Controller object is now linked to the Swift file. Why is this important? The View Controller file is used to define the layout of the objects on screen and the Swift file is where we “do things” with / to the objects e.g. if a user taps on a button, the code to handle that is in the Swift file.

Ok, next task is adding a Segue between the View Controllers.

A Segue (I think it’s pronounced Seg-way but I usually pronounce it Seg. Who knows!) is what we use to specify navigation links between View Controllers.

So, click on the little yellow button on the View Controller we want to navigate from:

and do that magical Control-drag from the button to the other View Controller:

still haven’t figure out how to screenshot a Control-drag!

When you “drop” the blue line, this box will pop up:

These are the different types of Segue available. We won’t go into what they all are today — we’ll just use the Present Modally option. This basically means that the View Controller that you go to (the “destination”) is placed on top / over the one you’re going from (the “source”).

When you select it, you’ll see a little arrow appear on the Storyboard between the View Controllers. Click on it and you’ll see the Source highlighted in blue:

Drag around the second View Controller and you’ll see the arrow expand / contract to follow:

Nice. And handy when you’ve loads of View Controllers and Segues.

We need to give the Segue an Identifier — so we can use it in code. Click on it and over on the right-hand panel, click the third fourth icon to bring up the Attributes Inspector:

In the Identifier field, type a name, like “mySegue”. Or “BruceTheHoon”, whatever you fancy! Feck it, I’m calling it BruceTheHoon! Bonus points for anyone who gets the reference!

Ok. Now we need to add two buttons:

  • one to the first View Controller to use the Segue and go to the second.
  • one to the second View Controller to close the second and return to the first.

So drag out a button and re-size it / change the properties as desired:

Now, open the Assistant Editor, by hitting the little button with the two circles, to show the ViewController.swift file alongside the Storyboard:

Control-drag from the Button to file and when it drops, select Action in the Connection dropdown and give it a Name, I type in“onGoButton” but again, you could call it anything … and hit Connect.

This should create a new function for you, that will be ran any time a user hits the Button:

Note that you have to Control-drag to add the function, you can’t just copy & paste — as the copy and pasted function wouldn’t be linked to the Button on the Storyboard.

Ok! Now add this line to the function:

performSegue(withIdentifier: “BruceTheHoon”, sender: self)

i.e.

This uses the function performSegue to actually go to the next View Controller. It takes two paramaters (value we can pass into functions) — an idendifier of a Segue: our “BruceTheHoon” identifier! Gold. And also a sender parameter which is almost always “self”. Ok, run the app and hit the button!

It should move you to the second (currently blank) View Controller.

Ok, presuming all went well there, now let’s add a Button to the second View Controller. This time we’ll use an image instead of text for the Button. so first, add a nice image to the Assets.xcassets folder; here I add an icon I obtained from icons8.com:

Back in our Storyboard, we drag out another Button, delete “Button” from the Default Title property:

and in the Image property we select the name of our image:

Now we Control-drag to the SecondViewController.swift file and add a new function, remembering to make it an Action and not an Outlet:

which results in:

Add this single line of code to the function:

dismiss(animated: true, completion: nil)

i.e.

This line of code simply “dismisses” the current View Controller.

Ok, run the app now — go to the second screen and hit the X Button — and you should be brought back to the first screen.

Ok, one more thing. Let’s send some data from the first View Controller to the second. To do this, we first create a variable in the SecondViewController.swift file:

var dataFromFirst :String = ""

i.e.

This creates a String variable which is empty.

Now add a Label to that View Controller and Control-drag to give it an Outlet variable, which I call “displayLabel”:

resulting in:

We’ll use that Label to display the value of the variable dataFromFirst so in viewDidLoad add this line:

displayLabel.text = dataFromFirst

i.e.

Ok, our second View Controller is now ready to accept and display some data from the first.

Go back to ViewController.swift and add a new function:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {}

This is a system provided function (that we add code to) that is ran before a Segue is actioned. Add this code:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {   let destVC : SecondViewController = segue.destination as! SecondViewController   destVC.dataFromFirst = "Hello there!"}

This is a bit odd, but it works. We’re creating an instance of the SecondViewController class and assigning a value to the dataFromFirst variable that we created a while ago! So when the Segue runs and the SecondViewController is shown on screen, the value we just assigned will be shown on the Label:

And we’re done!

Any comments or thoughts let me know below, or you can get me on Twitter or LinkedIn. Thanks, Andy

--

--

--

Creator of Boxapopa, the iOS game for young kids with zero ads, just fun! https://apps.apple.com/ie/app/boxapopa/id1550536188

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

An introduction to c# and the .Net library.

Automatically start the Alteryx Gallery via a Command Line script

Dagger 2 ( Caution: PLEASE TRY AT HOME ) Part 1

Building a custom view — a practical example

Hp Scan 3 For Mac Os High Sierra

Python program to sort the array element into ascending order

How to build an automated system that sends summarized ‘MarketWatch’ articles using R

How to Make Verified GitHub Commits

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
Andy O'Sullivan

Andy O'Sullivan

Creator of Boxapopa, the iOS game for young kids with zero ads, just fun! https://apps.apple.com/ie/app/boxapopa/id1550536188

More from Medium

Why SWIFT Is More Preferable Language For IOS App Development?

What is the Variables and Constants in Swift Language ?

Verifying JWS for StoreKit 2 in-app purchase