Prepared and tested with Xcode 10.2.1 and Swift 5 (2019-05-03)
In this tutorial we cover the following topics
General information
In this tutorial you can find some most frequently needed information about
segues
. Some of them are presented also in my other tutorials, for example in Multiview application (Swift). Here I try to collect all of them and extract so we can focus only on segues themselves but not other details not directly related with segues.
Project
- Step 1: create a new project
Create a new project- Select File | New | Project...
- Select Single View Application on the template selection sheet.
- As the product name enter
Swift iOS Segue
- Set the Language to Swift. Because we will not use tests in this tutorial, you can leave both test check boxes unchecked as well as make sure the check box labeled Use Core Data is also unchecked.
- Step 2: add all UI components
Create a new project- In the Project navigator select
Main.storyboard
file.
- Press
Command + Shift + L
to open library with UI components and drag a secondView Controller
and drop it in the editing area next to the existing one
- Select from the library a
Vertical Stack View
component and drag it to the firstView Controller
- Select from the library one
Text Field
and twoButton
s components and drag all of them to theVertical Stack View
we have just added in previous step
- Set all the necessary constraints:
Leading Space
,Top Space
andTrailing Space
- In the Project navigator select
- Step 3: create segue
- To Create segue between view controllers in the same storyboard file,
Control
-click an appropriate element in the first view controller (in our case this is a first button), drag to the target view controller and selectShow
from popup menu.
- To Create segue between view controllers in the same storyboard file,
- Step 4: rename buttons and set name for segue
- In
Attributes inspector
tab change name for a first button toGo with segue
and for a second button toGo without segue
Clik on the segue (arrow connecting controllers) and set its
Identifier
toSegueFromFirstToSecond
- In
- Step 5: segue code in
ViewController
controller- Select a first view controller either by clicking yellow circle on the top of
View Controller
(this is showned on the image below)
or by selecting thisView Controller
in theDocument Outline
(hidden in the image above). - Clik on the
Show the Assistant editor
to display this controller class' source code located inViewController.swift
file
- Create an action method connected to
Go without segue
button.Control
-click, drag from this button toViewController
class and name itpressButtonGoWithoutSegue
- Create an
textField
outlet for a text field.Control
-click and drag from a text field toViewController
class
- In the Project Navigator, right-click the Swift iOS Segue group and select New File....
- Choose Cocoa Touch Class from the iOS / Source section in the template dialog and then press Next
- Name the new class
VC_Second
, make it a subclass ofUIViewController
. Make sure that the Also create XIB file check box is not checked.
- Select a second view controller either by clicking yellow circle on the top of
View Controller
or by selecting thisView Controller
in theDocument Outline
. In theCustom Class
section ofIdentity inspector
tab on the right, changeClass
proprty toVC_Second
- Add (or modify) the following code in the
VC_Second.swift
1234567891011import UIKitclass VC_Second: UIViewController {var textData = ""override func viewDidLoad() {super.viewDidLoad()print("VC_Second:viewDidLoad:textData=\(textData)")}} - Add (or modify) the following code in the
ViewController.swift
1234567891011121314151617181920212223242526272829303132333435import UIKitclass ViewController: UIViewController {struct constants {static var segueIndetifier = "SegueFromFirstToSecond"}@IBOutlet weak var textField: UITextField!override func viewDidLoad() {super.viewDidLoad()}@IBAction func pressButtonGoWithoutSegue(_ sender: UIButton) {self.performSegue(withIdentifier: constants.segueIndetifier, sender: self)}override func prepare(for segue: UIStoryboardSegue, sender: Any?) {if (segue.identifier == constants.segueIndetifier) {let destVC = segue.destination as! VC_SeconddestVC.textData = textField.text!}}override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {if identifier == constants.segueIndetifier {if let string = textField.text, !string.isEmpty {return true}}print("Text field can't be empty")return false}} - Run emulator, leave a text field empty
and press theGo with segue
button
The message1Text field can't be emptyshould be displayed.
- Again leave a text field empty
but this time press theGo without segue
button
This time the message1VC_Second:viewDidLoad:textData=should be displayed and the second view should be presented.
- Fill a text field with
test
text
and press theGo with segue
button
The message1VC_Second:viewDidLoad:textData=testshould be displayed and the second view should be presented.
You may notice that calling
performSeguewithIdentifier
doesn't callshouldperformseguewithIdentifier
. This behaviour is perfectly natural, for the following reasons:shouldPerformSegueWithIdentifier
is used to make sure that a segue that has been set up in storyboard should be triggered, so it only gets called in the case of storyboard segue and gives you the chance to not actually perform the segue.- When you call
performSegueWithIdentifier
yourself,shouldPerformSegueWithIdentifier
is not called because it can be assumed that you know what you are doing. There would be no point in callingperformSegueWithIdentifier
but then return afalse
fromshouldPerformSegueWithIdentifier
.
- Select a first view controller either by clicking yellow circle on the top of
- Step 6: create an unwind segue
- To the second view controller add a button, place it in the middle of a view and name it
Go back
- In the view controller you are trying to go back to,
ViewController
in our case, add this code:
123456class ViewController: UIViewController {[...]@IBAction func myUnwindAction(_ segue: UIStoryboardSegue){}} - In the storyboard, go to the view you’re trying to unwind from,
VC_Second
in our case,Control
-click theGo back
button and drag it to theExit
icon located on top.
- From the popup menu, select the unwind segue action you just created in
ViewController
(myUnwindAction
in our case)
- If you want to
trigger unwind manually
, drag theview controller
yellow circle icon located on top of the view controller on the left to theExit
icon (also located on top but on the right). In this case you have to add also code similar to this
123@IBAction func someAction(_ sender: UIButton) {performSegue(withIdentifier: "unwindIdentifier", sender: self)}
wheresomeAction
is a name of an action (in this case trigerred by a button press), andunwindIdentifier
is an identifier of an unwind segue (remember to add this identifier toIdentifier
property ofStoryboard Unwind Segue
section inAttributes inspector
. - Now you can test if
Go back
button works (it should).
- To the second view controller add a button, place it in the middle of a view and name it