Using Storyboards in Xcode 15

Storyboarding is a feature built into Xcode that allows the various screens that comprise an iOS app and the navigation path through those screens to be visually assembled. Using the Interface Builder component of Xcode, the developer drags and drops view and navigation controllers onto a canvas and designs the user interface of each view in the usual manner. The developer then drags lines to link individual trigger controls (such as a button) to the corresponding view controllers that are to be displayed when the user selects the control. Having designed both the screens (referred to in the context of storyboarding as scenes) and specified the transitions between scenes (referred to as segues), Xcode generates all the code necessary to implement the defined behavior in the completed app. The transition style for each segue (page fold, cross dissolve, etc.) may also be defined within Interface Builder. Further, segues may be triggered programmatically when behavior cannot be graphically defined using Interface Builder.

Xcode saves the finished design to a storyboard file. Typically, an app will have a single storyboard file, though there is no restriction preventing using multiple storyboard files within a single app.

The remainder of this chapter will work through creating a simple app using storyboarding to implement multiple scenes with segues defined to allow user navigation.

Creating the Storyboard Example Project

Begin by launching Xcode and creating a new project named Storyboard using the iOS App template with the language menu set to Swift and the Storyboard Interface option selected. Then, save the project to a suitable location by clicking the Create button.

Accessing the Storyboard

Upon creating the new project, Xcode will have created what appears to be the usual collection of files for a single-view app, including a storyboard named file Main.storyboard. Select this file in the project navigator panel to view the storyboard canvas as illustrated in Figure 24-1.

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

The view displayed on the canvas is the view for the ViewController class created for us by Xcode when we selected the App template. The arrow pointing inwards to the left side of the view indicates that this is the initial view controller and will be the first view displayed when the app launches. To change the initial view controller, drag this arrow to any other scene in the storyboard and drop it in place.

Figure 24-1

Objects may be added to the view in the usual manner by displaying the Library panel and dragging and dropping objects onto the view canvas. For this example, drag a label and a button onto the view canvas. Using the properties panel, change the label text to Scene 1 and the button text to Go to Scene 2.

Figure 24-2

Using the Resolve Auto Layout Issues menu, select the Reset to Suggested Constraints option listed under All Views in View Controller.

It will be necessary first to establish an outlet to manipulate text displayed on the label object from within the app code. Select the label in the storyboard canvas and display the Assistant Editor (Editor -> Assistant). Check that the Assistant Editor is showing the content of the ViewController.swift file. Then, Ctrl-click on the label and drag the resulting line to just below the class declaration line in the Assistant Editor panel. In the resulting connection dialog, enter scene1Label as the outlet name and click on the Connect button. Upon completion of the connection, the top of the ViewController.swift file should read as follows:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var scene1Label: UILabel!
.
.Code language: Swift (swift)

Adding Scenes to the Storyboard

To add a second scene to the storyboard, drag a View Controller object from the Library panel onto the canvas. Figure 24-3 shows a second scene added to a storyboard:

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 24-3

Drag and drop a label and a button into the second scene and configure the objects so that the view appears as shown in Figure 24-4. Then, repeat the steps performed for the first scene to configure Auto Layout constraints on the two views.

Figure 24-4

As many scenes as necessary may be added to the storyboard, but we will use just two scenes for this exercise.

Having implemented the scenes, the next step is to configure segues between the scenes.

Configuring Storyboard Segues

As previously discussed, a segue is a transition from one scene to another within a storyboard. Within the example app, touching the Go To Scene 2 button will segue to scene 2. Conversely, the button on scene 2 is intended to return the user to scene 1. To establish a segue, hold down the Ctrl key on the keyboard, click over a control (in this case, the button on scene 1), and drag the resulting line to the scene 2 view. Upon releasing the mouse button, a menu will appear. Select the Present Modally menu option to establish the segue. Once the segue has been added, a connector will appear between the two scenes, as highlighted in Figure 24-5:

Figure 24-5

As more scenes are added to a storyboard, it becomes increasingly difficult to see more than a few scenes at one time on the canvas. To zoom out, double-click on the canvas. To zoom back in again, double-click once again on the canvas. The zoom level may also be changed using the plus and minus control buttons located in the status bar along the bottom edge of the storyboard canvas or by Ctrl-clicking on the storyboard canvas background to access a menu containing several zoom level options.

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Configuring Storyboard Transitions

Xcode allows changing the visual appearance of the transition that occurs during a segue. To change the transition, select the corresponding segue connector, display the Attributes Inspector, and modify the Transition setting. For example, in Figure 24-6, the transition has been changed to Cross Dissolve:

Figure 24-6

If animation is not required during the transition, turn off the Animates option. Run the app on a device or simulator and test that touching the “Go to Scene 2” button causes Scene 2 to appear.

Associating a View Controller with a Scene

At this point in the example, we have two scenes but only one view controller (the one created by Xcode when we selected the iOS App template). To add any functionality behind scene 2, it will also need a view controller. The first step is to add the class source file for a view controller to the project. Ctrl-click on the Storyboard target at the top of the project navigator panel and select New File… from the resulting menu. In the new file panel, select iOS in the top bar, followed by Cocoa Touch Class in the main panel, and click Next to proceed. On the options screen, ensure that the Subclass of menu is set to UIViewController and that the Also create XIB file option is deselected (since the view already exists in the storyboard there is no need for a XIB user interface file), name the class Scene2ViewController and proceed through the screens to create the new class file.

Select the Main.storyboard file in the project navigator panel and click the View Controller button located in the panel above the Scene 2 view, as shown in Figure 24-7:

Figure 24-7

With the view controller for scene 2 selected within the storyboard canvas, display the Identity Inspector (View -> Inspectors -> Identity) and change the Class from UIViewController to Scene2ViewController:

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 24-8

Scene 2 now has a view controller and corresponding Swift source file where code may be written to implement any required functionality.

Select the label object in scene 2 and display the Assistant Editor. Next, ensure that the Scene2ViewController.swift file is displayed in the editor, and then establish an outlet for the label named scene2Label.

Passing Data Between Scenes

One of the most common requirements when working with storyboards involves transferring data from one scene to another during a segue transition. Before the storyboard runtime environment performs a segue, a call is made to the prepare(for segue:) method of the current view controller. If any tasks need to be performed before the segue, implement this method in the current view controller and add code to perform any necessary tasks. Passed as an argument to this method is a segue object from which a reference to the destination view controller may be obtained and subsequently used to transfer data.

To see this in action, begin by selecting Scene2ViewController.swift and adding a new property variable:

import UIKit

class Scene2ViewController: UIViewController {

    @IBOutlet weak var scene2Label: UILabel!

    var labelText: String?
.
.
.Code language: Swift (swift)

This property will hold the text to be displayed on the label when the storyboard transitions to this scene. As such, some code needs to be added to the viewDidLoad method located in the Scene2ViewController.swift file:

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

override func viewDidLoad() {
    super.viewDidLoad()
    scene2Label.text = labelText
}Code language: Swift (swift)

Finally, select the ViewController.swift file and implement the prepare(for segue:) method as follows:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destination = segue.destination
                                as! Scene2ViewController
    destination.labelText = "Arrived from Scene 1"
}Code language: Swift (swift)

This method obtains a reference to the destination view controller and then assigns a string to the labelText property of the object so that it appears on the label.

Compile and rerun the app and note that the new label text appears when scene 2 is displayed. This is because we have, albeit using an elementary example, transferred data from one scene to the next.

Unwinding Storyboard Segues

The next step is configuring the button on scene 2 to return to scene 1. It might seem that the obvious choice is to implement a segue from the button in scene 2 to scene 1. Instead of returning to the original instance of scene 1, this would create an entirely new instance of the ViewController class. If a user were to perform this transition repeatedly, the app would continue using more memory and eventually be terminated by the operating system.

The app should instead make use of the Storyboard unwind feature. This involves implementing a method in the view controller of the scene to which the user is to be returned and then connecting a segue to that method from the source view controller. This enables an unwind action to be performed across multiple scene levels.

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

To implement this in our example app, begin by selecting the ViewController.swift file and implementing a method to be called by the unwind segue named returned:

@IBAction func returned(segue: UIStoryboardSegue) {
    scene1Label.text = "Returned from Scene 2"
}Code language: Swift (swift)

All this method requires for this example is that it sets some new text on the label object of scene 1. Once the method has been added, it is important to save the ViewController.swift file before continuing.

The next step is to establish the unwind segue. To achieve this, locate scene 2 within the storyboard canvas and Ctrl-click and drag from the button view to the “exit” icon (the orange button with the white square and the right-facing arrow pointing outward shown in Figure 24-9) in the panel located along the top edge of the scene view. Release the line and select the returnedWithSegue method from the resulting menu:

Figure 24-9

Once again, run the app and note that the button on scene 2 now returns to scene 1 and, in the process, calls the returned method resulting in the label on scene 1 changing.

Triggering a Storyboard Segue Programmatically

In addition to wiring up controls in scenes to trigger a segue, it is possible to initiate a preconfigured segue from within the app code. This can be achieved by assigning an identifier to the segue and then making a call to the performSegue(withIdentifier:) method of the view controller from which the segue is to be triggered.

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

To set the identifier of a segue, select it in the storyboard canvas, display the Attributes Inspector, and set the value in the Identifier field.

Assuming a segue with the identifier of SegueToScene1, this could be triggered from within code as follows:

self.performSegue(withIdentifier: "SegueToScene1", sender: self)Code language: Swift (swift)

Summary

The Storyboard feature of Xcode allows for the navigational flow between the various views in an iOS app to be visually constructed without the need to write code. In this chapter, we have covered the basic concepts behind storyboarding, worked through creating an example iOS app using storyboards, and explored the storyboard unwind feature.


Categories