SwiftUI Data Persistence using AppStorage and SceneStorage

It is a common requirement for an app to need to store small amounts of data which will persist through app restarts. This is particularly useful for storing user preference settings, or when restoring a scene to the exact state it was in last time it was accessed by the user. SwiftUI provides two property wrappers (@AppStorage and @SceneStorage) for the specific purpose of persistently storing small amounts of app data, details of which will be covered in this chapter.

The @SceneStorage Property Wrapper

The @SceneStorage property wrapper is used to store small amounts of data within the scope of individual app scene instances and is ideal for saving and restoring the state of a screen between app launches. Consider a situation where a user, partway through entering information into a form within an app, is interrupted by a phone call or text message, and places the app into the background. The user subsequently forgets to return to the app, complete the form and save the entered information. If the background app were to exit (either because of a device restart, the user terminating the app, or the system killing the app to free up resources) the partial information entered into the form would be lost. Situations such as this can be avoided, however, by using scene storage to retain and restore the data.

Scene storage is declared using the @SceneStorage property wrapper together with a key string value which is used internally to store the associated value. The following code, for example, declares a scene storage property designed to store a String value using a key name set to “city” with an initial default value set to an empty string:

@SceneStorage("city") var city: String = ""

Once declared, the stored property could, for example, be used in conjunction with a TextEditor as follows:

var body: some View {
    TextEditor(text: $city)
        .padding()
}

When implemented in an app, this will ensure that any text entered into the text field is retained within the scene through app restarts. If multiple instances of the scene are launched by the user on multi-windowing platforms such as iPadOS or macOS, each scene will have its own distinct copy of the saved value.

The @AppStorage Property Wrapper

The @SceneStorage property wrapper allows each individual scene within an app to have its own copy of stored data. In other words, the data stored by one scene is not accessible to any other scenes in the app (even other instances of the same scene). The @AppStorage property wrapper, on the other hand, is used to store data that is universally available throughout the entire app.

App Storage is built on top of UserDefaults, a feature which has been available in iOS for many years. Primarily provided as a way for apps to access and store default user preferences (such as language preferences or color choices), UserDefaults can also be used to store small amounts of data needed by the app in the form of keyvalue pairs.

As with scene storage, the @AppStorage property wrapper requires a string value to serve as a key and may be declared as follows:

@AppStorage("mystore") var mytext: String = ""

By default, data will be stored in the standard UserDefaults storage. It is also possible, however, to specify a custom App Group in which to store the data. App Groups allow apps to share data with other apps and targets within the same group. App Groups are assigned a name (typically similar to group.com.mydomain.myappname) and are enabled and configured within the Xcode project Signing & Capabilities screen. Figure 26-1, for example, shows a project target with App Groups enabled and a name set to group.com.ebookfrenzy.userdefaults:

Figure 26-1

The following @AppStorage declaration references an app group to use for storing data:

@AppStorage("mystore", 
  store: UserDefaults(
         suiteName: "group.com.ebookfrenzy.userdefaults")) 
              var mytext: String = ""

As with the @State property wrapper, changes to the stored value will cause the user interface to refresh to reflect the new data.

With the basics of app and scene storage covered, the remainder of this chapter will demonstrate these property wrappers in action.

Creating and Preparing the StorageDemo Project

Begin this tutorial by launching Xcode and selecting the options to create a new Multiplatform App project named StorageDemo.

Begin the project design by selecting the ContentView.swift file and changing the view body so that it contains a TabView as outlined below:

import SwiftUI
 
struct ContentView: View {
    
    var body: some View {
       
        TabView {
            SceneStorageView()
                .tabItem {
                    Image(systemName: "circle.fill")
                    Text("SceneStorage")
                }
 
            AppStorageView()
                .tabItem {
                    Image(systemName: "square.fill")
                    Text("AppStorage")
                }
         }
    }
}
.
.

Next, use the File -> New -> File… menu option to add two new SwiftUI View files named SceneStorageView and AppStorageView respectively.

Using Scene Storage

Edit the SceneStorageView.swift file and modify it so that it reads as follows:

import SwiftUI
 
struct SceneStorageView: View {
    
    @State private var editorText: String = ""
    
    var body: some View {
        TextEditor(text: $editorText)
            .padding(30)
            .font(.largeTitle)
    }
}

This declaration makes use of the TextEditor view. This is a view designed to allow multiline text to be displayed and edited within a SwiftUI app and includes scrolling when the displayed text extends beyond the viewable area. The TextEditor view is passed a binding to a state property into which any typed text will be stored (note that we aren’t yet using scene storage).

With the changes made, build and run the app on a device or simulator and, once launched, enter some text into the TextEditor view. Place the app into the background so that the device home screen appears, then terminate the app using the stop button located in the Xcode toolbar.

Run the app a second time and verify that the previously entered text has not been restored into the TextEditor view. Clearly this app would benefit from the use of scene storage.

Return to the SceneStorageView.swift file and convert the @State property to an @SceneStorage property as follows:

struct SceneStorageView: View {
 
        @SceneStorage("mytext") private var editorText = ""
.
.

Run the app again, enter some text, place it into the background and terminate it. This time, when the app is relaunched, the text will be restored into the TextEditor view.

When working with scene storage it is important to keep in mind that each instance of a scene has its own storage which is entirely separate from any other scenes. To experience this in action, run the StorageDemo app on an iPad device or simulator in landscape orientation. Once the app is running, swipe upward from the bottom of the screen to display the dock. Perform a long press on the launch icon for the StorageDemo app and, once the icon lifts from the screen, drag it to the right hand edge of the screen as shown in Figure 26-2:

Figure 26-2

On releasing the drag, the screen will be equally divided with two scene instances visible. Enter different text into each scene as shown in Figure 26-3 below:

Figure 26-3

Use the home button to place the app into the background, terminate the app and then re-launch it. On restarting, the two scenes will appear just as they were before the app was placed into the background, thereby demonstrating that each scene has a copy of its own stored data.

Using App Storage

The final task in this tutorial is to demonstrate the use of app storage. Within Xcode, edit the AppStorageView.swift file and modify it so that it reads as follows:

import SwiftUI
 
struct AppStorageView: View {
 
    @AppStorage("mytext") var editorText: String = "Sample Text"
    
    var body: some View {
        TextEditor(text: $editorText)
            .padding(30)
            .font(.largeTitle)
    }
}
.
.

With the changes made, run the app on the iPad once again and repeat the steps to display two scene instances side-by-side. Select the App Storage tab within both scenes and note that the scene instances are displaying the default sample text. Tap in one of the scenes and add some additional text. As text is added in one scene, the changes are reflected in the second scene as each character is typed:

Figure 26-4

Terminate the app while it is in the foreground (unlike scene storage, app storage data is stored in real-time, not just when the app is placed into the background) and relaunch it to confirm that the text changes were saved and restored.

Storing Custom Types

The @AppStorage and @SceneStorage property wrappers only allow values of certain types to be stored. Specifically Bool, Int, Double, String, URL and Data types. This means that any other type that needs to be stored must first be encoded as a Swift Data object in order to be stored and subsequently decoded when retrieved. Consider, for example, the following struct declaration and initialization:

struct UserName {
    var firstName: String
    var secondName: String
}
 
var username = UserName(firstName: "Mark", secondName: "Wilson")

Because UserName is not a supported type, it is not possible to store our username instance directly into app or scene-based storage. Instead, the instance needs to be encoded and encapsulated into a Data instance before it can be saved. The exact steps to perform the encoding and decoding will depend on the type of the data being stored. The key requirement, however, is that the type conforms to the Encodable and Decodable protocols. For example:

struct UserName: Encodable, Decodable {
    var firstName: String
    var secondName: String
}

The following example uses a JSON encoder to encode our username instance and store it using the @AppStorage property wrapper:

@AppStorage("username") var namestore: Data = Data()
.
.
let encoder = JSONEncoder()
 
if let data = try? encoder.encode(username) {
    namestore = data
}

When the time comes to retrieve the data from storage, the process is reversed using the JSON decoder:

let decoder = JSONDecoder()
 
if let name = try? decoder.decode(UserName.self, from: namestore) {
    username = name
}

Using this technique, it is even possible to store an image using either of the storage property wrappers, for example:

@AppStorage("myimage") var imagestore: Data = Data()
 
var image = UIImage(named: "profilephoto")
 
// Encode and store image
 
if let data = image!.pngData() {
    imagestore = data
}
 
// Retrieve and decode image
 
if let decodedImage: UIImage = UIImage(data: imagestore) {
     image = decodedImage
}

Summary

The @SceneStorage and @AppStorage property wrappers provide two ways to persistently store small amounts of data within a SwiftUI app. Scene storage is intended primarily for saving and restoring the state of a scene when an app is terminated while in the background. Each scene within an app has its own local scene storage which is not directly accessible to other areas of the app. App storage uses the UserDefaults system and is used for storing data that is to be accessible from anywhere within an app. Through the use of App Groups, app storage may also be shared between different targets within the same app project, or even entirely different apps. Changes to app storage are immediate regardless of whether the app is currently in the foreground or background.

Both the @AppStorage and @SceneStorage property wrappers support storing Bool, Int, Double, String, URL and Data types. Other types need to be encoded and encapsulated in Data objects before being placed into storage.

SwiftUI Observable and Environment Objects – A Tutorial

The chapter entitled “SwiftUI State Properties, Observable, State and Environment Objects” introduced the concept of observable and environment objects and explained how these are used to implement a data driven approach to app development in SwiftUI.

This chapter will build on the knowledge from the earlier chapter by creating a simple example project that makes use of both observable and environment objects.

About the ObservableDemo Project

Observable objects are particularly powerful when used to wrap dynamic data (in other words, data values that change repeatedly). To simulate data of this type, an observable data object will be created which makes use of the Foundation framework Timer object configured to update a counter once every second. This counter will be published so that it can be observed by views within the app project.

Initially, the data will be treated as an observable object and passed from one view to another. Later in the chapter, the data will be converted to an environment object so that it can be accessed by multiple views without being passed between views.

Creating the Project

Launch Xcode and select the option to create a new Multiplatform App project named ObservableDemo.

Adding the Observable Object

The first step after creating the new project is to add a data class implementing the ObservableObject protocol. Within Xcode, select the File -> New -> File… menu option and, in the resulting template dialog, select the Swift File option. Click the Next button and name the file TimerData before clicking the Create button.

With the TimerData.swift file loaded into the code editor, implement the TimerData class as follows:

import Foundation
import Combine
 
class TimerData : ObservableObject {
    
    @Published var timeCount = 0
    var timer : Timer?
    
    init() {    
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerDidFire), userInfo: nil, repeats: true)
    }
    
    @objc func timerDidFire() {
        timeCount += 1
    }
    
    func resetCount() {
        timeCount = 0
    }
}

The class is declared as implementing the ObservableObject protocol and contains an initializer which configures a Timer instance to call a function named timerDidFire() once every second. The timerDidFire() function, in turn, increments the value assigned to the timeCount variable. The timeCount variable is declared using the @Published property wrapper so that it can be observed from within views elsewhere in the project. The class also includes a method named resetCount() to reset the counter to zero.

Designing the ContentView Layout

The user interface for the app will consist of two screens, the first of which will be represented by the ContentView. Swift file. Select this file to load it into the code editor and modify it so that it reads as follows:

import SwiftUI
 
struct ContentView: View {
    
    @StateObject var timerData: TimerData = TimerData()
    
    var body: some View {
        
        NavigationView {
            VStack {
                Text("Timer count = \(timerData.timeCount)")
                
                    .font(.largeTitle)
                    .fontWeight(.bold)
                    .padding()
                
                Button(action: resetCount) {
                    Text("Reset Counter")
                }
            }
        }
    }
 
    func resetCount() {
        timerData.resetCount()
    }
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

With the changes made, use the Live Preview button to test the view. Once the Live Preview starts, the counter should begin incrementing:

Figure 25-1

Next, click on the Reset Counter button and verify that the counter restarts counting from zero. Now that the initial implementation is working, the next step is to add a second view which will also need access to the same observable object.

Adding the Second View

Select the File -> New -> File… menu option, this time choosing the SwiftUI View template option and naming the view SecondView. Edit the SecondView.swift file so that it reads as follows:

import SwiftUI
 
struct SecondView: View {
    
    @StateObject var timerData: TimerData
    
    var body: some View {
        
        VStack {
            Text("Second View")
                .font(.largeTitle)
            Text("Timer Count = \(timerData.timeCount)")
                .font(.headline)
        }
        .padding()
    }
}
 
struct SecondView_Previews: PreviewProvider {
    static var previews: some View {
        SecondView(timerData: TimerData())
    }
}

Use Live Preview to test that the layout matches Figure 25-2 and that the timer begins counting.

In the Live Preview, the view has its own instance of TimerData which was configured in the SecondView_ Previews declaration. To make sure that both ContentView and SecondView are using the same TimerData instance, the observed object needs to be passed to the SecondView when the user navigates to the second screen.

Figure 25-2

Adding Navigation

A navigation link now needs to be added to ContentView and configured to navigate to the second view. Open the ContentView.swift file in the code editor and add this link as follows:

var body: some View {
    
    NavigationView {
        VStack {
            Text("Timer count = \(timerData.timeCount)")
            
                .font(.largeTitle)
                .fontWeight(.bold)
                .padding()
            
            Button(action: resetCount) {
                Text("Reset Counter")
            }
            
            NavigationLink(destination: 
                       SecondView(timerData: timerData)) {
                Text("Next Screen")
            }
            .padding()
        }
    }
}

Once again using Live Preview, test the ContentView and check that the counter increments. Taking note of the current counter value, click on the Next Screen link to display the second view and verify that counting continues from the same number. This confirms that both views are subscribed to the same observable object instance.

Using an Environment Object

The final step in this tutorial is to convert the observable object to an environment object. This will allow both views to access the same TimerData object without the need for a reference to be passed from one view to the other.

This change does not require any modifications to the TimerData.swift class declaration and only minor changes are needed within the two SwiftUI view files. Starting with the ContentView.swift file, modify the navigation link destination so that timerData is no longer passed through to SecondView. Also add a call to the environmentObject() modifier to insert the timerData instance into the view hierarchy environment:

import SwiftUI
 
struct ContentView: View {
    
    @StateObject var timerData: TimerData = TimerData()
        
    var body: some View {
        
        NavigationView {
.
.
                NavigationLink(destination: SecondView(timerData: timerData)) {
                    Text("Next Screen")
                }
                .padding()
            }
        }
        .environmentObject(timerData)
    }
.
.
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Next, modify the SecondView.swift file so that it reads as follows:

import SwiftUI
 
struct SecondView: View {
    
    @EnvironmentObject var timerData: TimerData
    
    var body: some View {
        
        VStack {
            Text("Second View")
                .font(.largeTitle)
            Text("Timer Count = \(timerData.timeCount)")
                .font(.headline)
        }.padding()
    }
}
 
struct SecondView_Previews: PreviewProvider {
    static var previews: some View {
        SecondView().environmentObject(TimerData())
    }
}

Test the project one last time, either using Live Preview or by running on a physical device or simulator and check that both screens are accessing the same counter data via the environment.

Summary

This chapter has worked through a tutorial that demonstrates the use of observed and environment objects to bind dynamic data to the views in a user interface, including implementing an observable object, publishing a property, subscribing to an observable object and the use of environment objects.

SwiftUI Concurrency and Lifecycle Event Modifiers

One of the key strengths of SwiftUI is that, through the use of features such as views, state properties, and observable objects, much of the work required in making sure an app handles lifecycle changes correctly is performed automatically.

It is still often necessary, however, to perform additional actions when certain lifecycle events occur. An app might, for example, need to perform a sequence of actions at the point that a view appears or disappears within a layout. Similarly, an app may need to execute some code each time a value changes or to detect when a view becomes active or inactive. It will also be a common requirement to launch one or more asynchronous tasks at the beginning of a view lifecycle.

All of these requirements and more can be met by making use of a set of event modifiers provided by SwiftUI.

Since event modifiers are best understood when seen in action, this chapter will create a project which makes use of the four most commonly used modifiers.

Creating the LifecycleDemo Project

Launch Xcode and select the option to create a new Multiplatform App project named LifecycleDemo.

Designing the App

Begin by editing the ContentView.swift file and modifying the body declaration so that it reads as follows:

import SwiftUI
 
struct ContentView: View {
    
    var body: some View {
        TabView {
            TabView {
                FirstTabView()
                    .tabItem {
                        Image(systemName: "01.circle")
                        Text("First")
                    }
 
                SecondTabView()
                    .tabItem {
                        Image(systemName: "02.circle")
                        Text("Second")
                    }
            }
        }
    }
}

Select the Xcode File -> New -> File… menu option and in the resulting template panel, select the SwiftUI View option from the User Interface section as shown in Figure 26-1 below:

Figure 26-1

Click the Next button, name the file FirstTabView.swift, and select the Shared folder as the save location before clicking on the Create button. With the new file loaded into the editor, change the Text view to read “View One”.

Repeat the above steps to create a second SwiftUI view file named SecondTabView.swift with the Text view set to “View Two”

The onAppear and onDisappear Modifiers

The most basic and frequently used modifiers are onAppear() and onDisappear(). When applied to a view, these modifiers allow actions to be performed at the point that the view appears or disappears. Within the FirstTabView.swift file, add both modifiers to the Text view as follows:

import SwiftUI
 
struct FirstTabView: View {
   
    var body: some View {
 
        Text("View One")
            .onAppear(perform: {
                print("onAppear triggered")
            })
            .onDisappear(perform: {
                print("onDisappeared triggered")
            })
    }
}

Using Live Preview in debug mode, test the app and note that the diagnostic output appears in the console panel when the app first appears (if the output does not appear, try running the app on a device or simulator). Click on the second tab to display SecondTabView at which point the onDisappear modifier will be triggered. Display the first tab once again and verify that the onAppear diagnostic is output to the console.

The onChange Modifier

In basic terms, the onChange() modifier should be used when an action needs to be performed each time a state changes within an app. This, for example, allows actions to be triggered each time the value of a state property changes. As we will explore later in the chapter, this modifier is also particularly useful when used in conjunction with the ScenePhase environment property.

To experience the onChange() modifier in action, begin by editing the SecondTabView.swift file so that it reads as follows:

import SwiftUI
 
struct SecondTabView: View {
    
    @State private var text: String = ""
    
    var body: some View {
        TextEditor(text: $text)
            .padding()
            .onChange(of: text, perform: { value in
                print("onChange triggered")
            })
    }
}
 
struct SecondTabView_Previews: PreviewProvider {
    static var previews: some View {
        SecondTabView()
    }
}

Test the app again and note that the event is triggered for each keystroke within the TextEditor view.

ScenePhase and the onChange Modifier

ScenePhase is an @Environment property that is used by SwiftUI to store the state of the current scene. When changes to ScenePhase are monitored by the onChange() modifier, an app can take action, for example, when the scene moves between the foreground and background or when it becomes active or inactive. This technique can be used on any view or scene but is also useful when applied to the App declaration. For example, edit the LifecycleDemoApp.swift file and modify it so that it reads as follows:

import SwiftUI
 
@main
struct LifecycleDemoApp: App {
    
    @Environment(\.scenePhase) private var scenePhase
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .onChange(of: scenePhase, perform: { phase in
                switch phase {
                    case .active:
                        print("Active")
                    case .inactive:
                        print("Inactive")
                    case .background:
                        print("Background")
                    default:
                        print("Unknown scenephase")
                }
            })
    }
}

When applied to the window group in this way, the scene phase will be based on the state of all scenes within the app. In other words, the phase will be set to active if any scene is currently active and will only be set to inactive when all scenes are inactive.

When applied to an individual view, on the other hand, the phase state will reflect only that of the scene in which the view is located. The modifier could, for example, have been applied to the content view instead of the window group as follows:

.
.
var body: some Scene {
    WindowGroup {
        ContentView()
            .onChange(of: scenePhase, perform: { phase in
.
.
 
    }
.
.

Run the app on a device or simulator and place the app into the background. The console should show that the scene phase changed to inactive state followed by the background phase. On returning the app to the foreground the active phase will be entered. The three scene phases can be summarized as follows:

  • active – The scene is in the foreground, visible, and responsive to user interaction.
  • inactive –The scene is in the foreground and visible to the user but not interactive.
  • background – The scene is not visible to the user.

Launching Concurrent Tasks

The chapter entitled “An Overview of Swift Structured Concurrency” covered the topic of structured concurrency in Swift but did not explain how asynchronous tasks can be launched in the context of a SwiftUI view. In practice, all of the techniques described in that earlier chapter still apply when working with SwiftUI. All that is required is a call to the task() modifier on a view together with a closure containing the code to be executed. This code will be executed within a new concurrent task at the point that the view is created. We can, for example, modify the FirstTabView to display a different string on the Text view using an asynchronous task:

import SwiftUI
 
struct FirstTabView: View {
    
    @State var title = "View One"
    
    var body: some View {
        Text(title)
            .onAppear(perform: {
                print("onAppear triggered")
            })
            .onDisappear(perform: {
                print("onDisappeared triggered")
            })
            .task(priority: .background) {
                title = await changeTitle()
            }
 
    }
    
    func changeTitle() async -> String {
        Thread.sleep(forTimeInterval: 5)
        return "Async task complete"
    }
}
 
struct FirstTabView_Previews: PreviewProvider {
    static var previews: some View {
        FirstTabView()
    }
}

When the view is created, a task is launched with an optional priority setting. The task calls a function named changeTitle() and then waits for the code to execute asynchronously.

The changeTitle() function puts the thread to sleep for 5 seconds to simulate a long-running task before returning a new title string. This string is then assigned to the title state variable where it will appear on Text view. Build and run the app and verify that the tabs remain responsive during the 5-second delay and that the new title appears on the first tab.

Summary

SwiftUI provides a collection of modifiers designed to allow actions to be taken in the event of lifecycle changes occurring in a running app. The onAppear() and onDisappear() modifiers can be used to perform actions when a view appears or disappears from view within a user interface layout. The onChange() modifier, on the other hand, is useful for performing tasks each time the value assigned to a property changes.

The ScenePhase environment property, when used with the onChange() modifier, allows an app to identify when the state of a scene changes. This is of particular use when an app needs to know when it moves between foreground and background modes. Asynchronous tasks can be launched when a view is created using the task() modifier.

A SwiftUI Example Tutorial

Now that some of the fundamentals of SwiftUI development have been covered, this chapter will begin to put this theory into practice through the design and implementation of an example SwiftUI-based project.

The objective of this chapter is to demonstrate the use of Xcode to design a simple interactive user interface, making use of views, modifiers, state variables, and some basic animation techniques. Throughout the course of this tutorial, a variety of different techniques will be used to add and modify views. While this may appear to be inconsistent, the objective is to gain familiarity with the different options available.

Creating the Example Project

Start Xcode and select the option to create a new project. On the template selection screen, make sure Multiplatform is selected and choose the App option as shown in Figure 23-1 before proceeding to the next screen:

Figure 23-1

On the project options screen, name the project SwiftUIDemo before clicking Next to proceed to the final screen. Choose a suitable filesystem location for the project and click on the Create button.

Reviewing the Project

Once the project has been created it will contain the SwiftUIDemoApp.swift file along with a SwiftUI View file named ContentView.swift which should have loaded into the editor and preview canvas ready for modification (if it has not loaded, simply select it in the project navigator panel). From the target device menu (Figure 23-2) select an iPhone 13 simulator:

Figure 23-2

If the preview canvas is in the paused state, click on the Resume button to build the project and display the preview:

Figure 23-3

Adding a VStack to the Layout

The view body currently consists of a single Text view of which we will make use in the completed project. A container view now needs to be added so that other views can be included in the layout. For the purposes of this example, the layout will be stacked vertically so a VStack needs to be added to the layout.

Within the code editor, select the Text view entry, hold down the Command key on the keyboard and perform a left-click. From the resulting menu, select the Embed in VStack option:

Figure 23-4

Once the Text view has been embedded into the VStack the declaration will read as follows:

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, world!")
                .padding()
        }
    }
}

Before modifying the view, remove the padding() modifier from the Text view:

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, world!")

        }
    }
}

Adding a Slider View to the Stack

The next item to be added to the layout is a Slider view. Within Xcode, display the Library panel by clicking on the ‘+’ button highlighted in Figure 23-5, locate the Slider in the View list and drag it over the top of the existing Text view within the preview canvas. Make sure the notification panel (also highlighted in Figure 23-5) indicates that the view is going to be inserted into the existing stack (as opposed to being placed in a new vertical stack) before dropping the view into place.

Figure 23-5

Once the slider has been dropped into place, the view implementation should read as follows:

struct ContentView: View {
    var body: some View {
        VStack {
            VStack {
                Text("Hello, world!")
                Slider(value: Value)
            }   
        }
    }
}

Adding a State Property

The slider is going to be used to control the degree to which the Text view is to be rotated. As such, a binding needs to be established between the Slider view and a state property into which the current rotation angle will be stored. Within the code editor, declare this property and configure the Slider to use a range between 0 and 360 in increments of 0.1:

struct ContentView: View {
    
    @State private var rotation: Double = 0
    
    var body: some View {
        VStack {
            VStack {
                Text("Hello, world!")
                Slider(value: $rotation, in: 0 ... 360, step: 0.1)
            }     
        }
    }
}

Note that since we are declaring a binding between the Slider view and the rotation state property it is prefixed by a ‘$’ character.

Adding Modifiers to the Text View

The next step is to add some modifiers to the Text view to change the font and to adopt the rotation value stored by the Slider view. Begin by displaying the Library panel, switch to the modifier list and drag and drop a font modifier onto the Text view entry in the code editor:

Figure 23-6

Select the modifier line in the editor, refer to the Attributes inspector panel and change the font property from Title to Large Title as shown in Figure 23-7:

Figure 23-7

Note that the modifier added above does not change the font weight. Since modifiers may also be added to a view from within the Attributes inspector, take this opportunity to change the setting of the Weight menu from Inherited to Heavy.

On completion of these steps, the View body should read as follows:

var body: some View {
    VStack {
        VStack {
            Text("Hello, world!")
                .font(.largeTitle)
                .fontWeight(.heavy)
                Slider(value: $rotation, in: 0 ... 360, step: 0.1)
        }
    }
}

Adding Rotation and Animation

The next step is to add the rotation and animation effects to the Text view using the value stored by the Slider (animation is covered in greater detail in the “SwiftUI Animation and Transitions” chapter). This can be implemented using a modifier as follows:

.
.
Text("Hello, world!")
    .font(.largeTitle)
    .fontWeight(.heavy)
    .rotationEffect(.degrees(rotation))
.
.

Note that since we are simply reading the value assigned to the rotation state property, as opposed to establishing a binding, the property name is not prefixed with the ‘$’ sign notation.

Click on the Live Preview button (indicated by the arrow in Figure 23-8), wait for the code to compile, then use the slider to rotate the Text view:

Figure 23-8

Next, add an animation modifier to the Text view to animate the rotation over 5 seconds using the Ease In Out effect:

Text("Hello, world!")
    .font(.largeTitle)
    .fontWeight(.heavy)
    .rotationEffect(.degrees(rotation))
    .animation(.easeInOut(duration: 5), value: rotation)

Use the slider once again to rotate the text and note that rotation is now smoothly animated.

Adding a TextField to the Stack

In addition to supporting text rotation, the app will also allow custom text to be entered and displayed on the Text view. This will require the addition of a TextField view to the project. To achieve this, either directly edit the View structure or use the Library panel to add a TextField so that the structure reads as follows (note also the addition of a state property in which to store the custom text string and the change to the Text view to use this property):

struct ContentView: View {
    
    @State private var rotation: Double = 0
    @State private var text: String = "Welcome to SwiftUI"
    
    var body: some View {
        VStack {
            VStack {
                Text(text)
                    .font(.largeTitle)
                    .fontWeight(.heavy)
                    .rotationEffect(.degrees(rotation))
                    .animation(.easeInOut(duration: 5))
 
                Slider(value: $rotation, in: 0 ... 360, step: 0.1)
            
                TextField("Enter text here", text: $text)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
            }
        }
    }
}

When the user enters text into the TextField view, that text will be stored in the text state property and will automatically appear on the Text view via the binding. Return to the preview canvas and make sure that the changes work as expected.

Adding a Color Picker

The final view to be added to the stack before we start to tidy up the layout is a Picker view. The purpose of this view will be to allow the foreground color of the Text view to be chosen by the user from a range of color options. Begin by adding some arrays of color names and Color objects, together with a state property to hold the current array index value as follows:

import SwiftUI
 
struct ContentView: View {
    
    var colors: [Color] = [.black, .red, .green, .blue]
    var colornames = ["Black", "Red", "Green", "Blue"]
    
    @State private var colorIndex = 0
    @State private var rotation: Double = 0
    @State private var text: String = "Welcome to SwiftUI"

With these variables configured, display the Library panel, locate the Picker in the Views screen and drag and drop it beneath the TextField view in either the code editor or preview canvas so that it is embedded in the existing VStack layout. Once added, the view entry will read as follows:

Picker(selection: .constant(1, label: Text("Picker") {
    Text("1").tag(1)
    Text("2").tag(2)
}

The Picker view needs to be configured to store the current selection in the colorIndex state property and to display an option for each color name in the colorNames array. To make the Picker more visually appealing, the background color for each Text view will be changed to the corresponding color in the colors array.

For the purposes of iterating through the colorNames array, the code will make use of the SwiftUI ForEach structure. At first glance, ForEach looks like just another Swift programing language control flow statement. In fact, ForEach is very different from the Swift forEach() array method outlined earlier in the book.

ForEach is itself a SwiftUI view structure designed specifically to generate multiple views by looping through a data set such as an array or range. Within the editor, modify the Picker view declaration so that it reads as follows:

Picker(selection: $colorIndex, label: Text("Color")) {
    ForEach (0 ..< colornames.count)  { color in
        Text(colornames[color])
            .foregroundColor(colors[color])
    }
}

In the above implementation, ForEach is used to loop through the elements of the colornames array, generating a Text view for each color, setting the displayed text and background color on each view accordingly.

The ForEach loop in the above example is contained within a closure expression. As outlined in the chapter entitled “Swift Functions, Methods and Closures” this expression can be simplified using shorthand argument names. Using this technique, modify the Picker declaration so that it reads as follows:

Picker(selection: $colorIndex, label: Text("Color")) {
    ForEach (0 ..< colornames.count) { color in
        Text(colornames[$0])
            .foregroundColor(colors[$0])
    }
}

The Picker view may be configured to display the color choices in a range of different ways. For this project, we need to select the WheelPickerStyle (.wheel) style via the pickerStyle() modifier:

Picker(selection: $colorIndex, label: Text("Color")) {
    ForEach (0 ..< colornames.count) {
        Text(colornames[$0])
            .foregroundColor(colors[$0])
    }
}
.pickerStyle(.wheel)

Remaining in the code editor, locate the Text view and add a foreground color modifier to set the foreground color based on the current Picker selection value:

Text(text)
    .font(.largeTitle)
    .fontWeight(.heavy)
    .rotationEffect(.degrees(rotation))
    .animation(.easeInOut(duration: 5))
    .foregroundColor(colors[colorIndex])

Test the app in the preview canvas and confirm that the Picker view appears with all of the color names using the corresponding foreground color and that color selections are reflected in the Text view.

Tidying the Layout

Up until this point the focus of this tutorial has been on the appearance and functionality of the individual views. Aside from making sure the views are stacked vertically, however, no attention has been paid to the overall appearance of the layout. At this point the layout should resemble that shown in Figure 23-9:

Figure 23-9

The first improvement that is needed is to add some space around the Slider, TextField and Picker views so that they are not so close to the edge of the device display. To implement this, we will add some padding modifiers to the views:

Slider(value: $rotation, in: 0 ... 360, step: 0.1)
    .padding()
 
TextField("Enter text here", text: $text)
    .textFieldStyle(RoundedBorderTextFieldStyle())
    .padding()
 
Picker(selection: $colorIndex, label: Text("Color")) {
    ForEach (0 ..< colornames.count) {
        Text(colornames[$0])
            .foregroundColor(colors[$0])
    }
}
.pickerStyle(.wheel)
.padding()

Next, the layout would probably look better if the Views were evenly spaced. One way to implement this is to add some Spacer views before and after the Text view:

VStack {
        Spacer()
        Text(text)
            .font(.largeTitle)
            .fontWeight(.heavy)
            .rotationEffect(.degrees(rotation))
            .animation(.easeInOut(duration: 5))
            .foregroundColor(colors[colorIndex])
        Spacer()
            Slider(value: $rotation, in: 0 ... 360, step: 0.1)
                .padding()
.
.

The Spacer view provides a flexible space between views that will expand and contract based on the requirements of the layout. If a Spacer is contained in a stack it will resize along the stack axis. When used outside of a stack container, a Spacer view can resize both horizontally and vertically.

To make the separation between the Text view and the Slider more obvious, also add a Divider view to the layout:

.
.
VStack {
    Spacer()
    Text(text)
        .font(.largeTitle)
        .fontWeight(.heavy)
        .rotationEffect(.degrees(rotation))
        .animation(.easeInOut(duration: 5))
        .foregroundColor(colors[colorIndex])
    Spacer()
    Divider()
.
.

The Divider view draws a line to indicate separation between two views in a stack container.

With these changes made, the layout should now appear in the preview canvas as shown in Figure 23-10:

Figure 23-10

Summary

The goal of this chapter has been to put into practice some of the theory covered in the previous chapters through the creation of an example app project. In particular, the tutorial made use of a variety of techniques for adding views to a layout in addition to the use of modifiers and state property bindings. The chapter also introduced the Spacer and Divider views and made use of the ForEach structure to dynamically generate views from a data array.

SwiftUI State Properties, Observable, State and Environment Objects

Earlier chapters have described how SwiftUI emphasizes a data driven approach to app development whereby the views in the user interface are updated in response to changes in the underlying data without the need to write handling code. This approach is achieved by establishing a publisher and subscriber binding between the data and the views in the user interface.

SwiftUI offers four options for implementing this behavior in the form of state properties, observable objects, state objects and environment objects, all of which provide the state that drives the way the user interface appears and behaves. In SwiftUI, the views that make up a user interface layout are never updated directly within code. Instead, the views are updated automatically based on the state objects to which they have been bound as they change over time.

This chapter will describe these four options and outline when they should be used. Later chapters (“A SwiftUI Example Tutorial” and “SwiftUI Observable and Environment Objects – A Tutorial”) will provide practical examples that demonstrates their use.

State Properties

The most basic form of state is the state property. State properties are used exclusively to store state that is local to a view layout such as whether a toggle button is enabled, the text being entered into a text field or the current selection in a Picker view. State properties are used for storing simple data types such as a String or an Int value and are declared using the @State property wrapper, for example:

struct ContentView: View {
 
    @State private var wifiEnabled = true
    @State private var userName = ""
 
    var body: some View {
.
.

Note that since state values are local to the enclosing view they should be declared as private properties.

Every change to a state property value is a signal to SwiftUI that the view hierarchy within which the property is declared needs to be re-rendered. This involves rapidly recreating and displaying all of the views in the hierarchy. This, in turn, has the effect of ensuring that any views that rely on the property in some way are updated to reflect the latest value.

Once declared, bindings can be established between state properties and the views contained in the layout. Changes within views that reference the binding are then automatically reflected in the corresponding state property. A binding could, for example, be established between a Toggle view and the Boolean wifiEnabled property declared above. Whenever the user switches the toggle, SwiftUI will automatically update the state property to match the new toggle setting.

A binding to a state property is implemented by prefixing the property name with a ‘$’ sign. In the following example, a TextField view establishes a binding to the userName state property to use as the storage for text entered by the user:

struct ContentView: View {
    
    @State private var wifiEnabled = true
    @State private var userName = ""
 
    var body: some View {
        VStack {
            TextField("Enter user name", text: $userName)
        }
    }
}

With each keystroke performed as the user types into the TextField the binding will store the current text into the userName property. Each change to the state property will, in turn, cause the view hierarchy to be rerendered by SwiftUI.

Of course, storing something in a state property is only one side of the process. As previously discussed, a change of state usually results in a change to other views in the layout. In this case, a Text view might need to be updated to reflect the user’s name as it is being typed. This can be achieved by declaring the userName state property value as the content for a Text view:

var body: some View {
   VStack {
        TextField("Enter user name", text: $userName)
        Text(userName)
    }
}

As the user types, the Text view will automatically update to reflect the user’s input. Note that in this case the userName property is declared without the ‘$’ prefix. This is because we are now referencing the value assigned to the state property (i.e. the String value being typed by the user) instead of a binding to the property.

Similarly, the hypothetical binding between a Toggle view and the wifiEnabled state property described above could be implemented as follows:

var body: some View {
    
    VStack {
        Toggle(isOn: $wifiEnabled) {
            Text("Enable Wi-Fi")
        }
        TextField("Enter user name", text: $userName)
        Text(userName)  
        Image(systemName: wifiEnabled ? "wifi" : "wifi.slash")
    }
}

In the above declaration, a binding is established between the Toggle view and the state property. The value assigned to the property is then used to decide which image is to be displayed on an Image view.

State Binding

A state property is local to the view in which it is declared and any child views. Situations may occur, however, where a view contains one or more subviews which may also need access to the same state properties. Consider, for example, a situation whereby the Wi-Fi Image view in the above example has been extracted into a subview:

.
.
    VStack {
        Toggle(isOn: $wifiEnabled) {
            Text("Enable WiFi")
        }
        TextField("Enter user name", text: $userName)
        WifiImageView()
    }
}
.
.
struct WifiImageView: View {
 
    var body: some View {
        Image(systemName: wifiEnabled ? "wifi" : "wifi.slash")
    }
}

Clearly the WifiImageView subview still needs access to the wifiEnabled state property. As an element of a separate subview, however, the Image view is now out of the scope of the main view. Within the scope of WifiImageView, the wifiEnabled property is an undefined variable.

This problem can be resolved by declaring the property using the @Binding property wrapper as follows:

struct WifiImageView: View {
    
    @Binding var wifiEnabled : Bool
    
    var body: some View {
        Image(systemName: wifiEnabled ? "wifi" : "wifi.slash")
    }
}

Now, when the subview is called, it simply needs to be passed a binding to the state property:

WifiImageView(wifiEnabled: $wifiEnabled)

Observable Objects

State properties provide a way to locally store the state of a view, are available only to the local view and, as such, cannot be accessed by other views unless they are subviews and state binding is implemented. State properties are also transient in that when the parent view goes away the state is also lost. Observable objects, on the other hand are used to represent persistent data that is both external and accessible to multiple views.

An Observable object takes the form of a class or structure that conforms to the ObservableObject protocol. Though the implementation of an observable object will be application specific depending on the nature and source of the data, it will typically be responsible for gathering and managing one or more data values that are known to change over time. Observable objects can also be used to handle events such as timers and notifications.

The observable object publishes the data values for which it is responsible as published properties. Observer objects then subscribe to the publisher and receive updates whenever changes to the published properties occur. As with the state properties outlined above, by binding to these published properties SwiftUI views will automatically update to reflect changes in the data stored in the observable object.

Observable objects are part of the Combine framework, which was first introduced with iOS 13 to make it easier to establish relationships between publishers and subscribers.

The Combine framework provides a platform for building custom publishers for performing a variety of tasks from the merging of multiple publishers into a single stream to transforming published data to match subscriber requirements. This allows for complex, enterprise level data processing chains to be implemented between the original publisher and resulting subscriber. That being said, one of the built-in publisher types will typically be all that is needed for most requirements. In fact, the easiest way to implement a published property within an observable object is to simply use the @Published property wrapper when declaring a property. This wrapper simply sends updates to all subscribers each time the wrapped property value changes.

The following structure declaration shows a simple observable object declaration with two published properties:

import Foundation
import Combine
 
class DemoData : ObservableObject {
    
    @Published var userCount = 0
    @Published var currentUser = ""
    
    init() {
        // Code here to initialize data
        updateData()
    }
    
    func updateData() {
        // Code here to keep data up to date 
    }
}

A subscriber uses either the @ObservedObject or @StateObject property wrapper to subscribe to the observable object. Once subscribed, that view and any of its child views access the published properties using the same techniques used with state properties earlier in the chapter. A sample SwiftUI view designed to subscribe to an instance of the above DemoData class might read as follows:

import SwiftUI
 
struct ContentView: View {
    
    @ObservedObject var demoData : DemoData = DemoData()
    
    var body: some View {
        Text("\(demoData.currentUser), you are user number \(demoData.userCount)")
    }
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

State Objects

Introduced in iOS 14, the State Object property wrapper (@StateObject) is an alternative to the @ObservedObject wrapper. The key difference between a state object and an observed object is that an observed object reference is not owned by the view in which it is declared and, as such, is at risk of being destroyed or recreated by the SwiftUI system while still in use (for example as the result of the view being re-rendered).

Using @StateObject instead of @ObservedObject ensures that the reference is owned by the view in which it is declared and, therefore, will not be destroyed by SwiftUI while it is still needed, either by the local view in which it is declared, or any child views.

As a general rule, unless there is a specific need to use @ObservedObject, the recommendation is to use a State Object to subscribe to observable objects. In terms of syntax, the two are entirely interchangeable:

import SwiftUI
 
struct ContentView: View {
    
    @StateObject var demoData : DemoData = DemoData()
    
    var body: some View {
        Text("\(demoData.currentUser), you are user number \(demoData.userCount)")
    }
}
.
.

Environment Objects

Observed objects are best used when a particular state needs to be used by a few SwiftUI views within an app. When one view navigates to another view which needs access to the same observed or state object, the originating view will need to pass a reference to the observed object to the destination view during the navigation (navigation will be covered in the chapter entitled “SwiftUI Lists and Navigation”). Consider, for example, the following code:

.
.
@StateObject var demoData : DemoData = DemoData()
.
.
NavigationLink(destination: SecondView(demoData)) {
    Text("Next Screen")
}

In the above declaration, a navigation link is used to navigate to another view named SecondView, passing through a reference to the demoData observed object.

While this technique is acceptable for many situations, it can become complex when many views within an app need access to the same observed object. In this situation, it may make more sense to use an environment object.

An environment object is declared in the same way as an observable object (in that it must conform to the ObservableObject protocol and appropriate properties must be published). The key difference, however, is that the object is stored in the environment of the view in which it is declared and, as such, can be accessed by all child views without needing to be passed from view to view.

Consider the following example observable object declaration:

class SpeedSetting: ObservableObject {
    @Published var speed = 0.0
}

Views needing to subscribe to an environment object simply reference the object using the @EnvironmentObject property wrapper instead of the @StateObject or @ObservedObject wrapper. For example, the following views both need access to the same SpeedSetting data:

struct SpeedControlView: View {
    @EnvironmentObject var speedsetting: SpeedSetting
 
    var body: some View {
        Slider(value: $speedsetting.speed, in: 0...100)
    }
}
 
struct SpeedDisplayView: View {
    @EnvironmentObject var speedsetting: SpeedSetting
 
    var body: some View {
        Text("Speed = \(speedsetting.speed)")
    }
}

At this point we have an observable object named SpeedSetting and two views that reference an environment object of that type, but we have not yet initialized an instance of the observable object. The logical place to perform this task is within the parent view of the above sub-views. In the following example, both views are sub-views of main ContentView:

struct ContentView: View {
    let speedsetting = SpeedSetting()
 
    var body: some View {
        VStack {
            SpeedControlView()
            SpeedDisplayView()
        }
    }
}

If the app were to run at this point, however, it would crash shortly after launching with the following diagnostics:

Thread 1: Fatal error: No ObservableObject of type SpeedSetting found. A View. environmentObject(_:) for SpeedSetting may be missing as an ancestor of this view.

The problem here is that while we have created an instance of the observable object within the ContentView declaration, we have not yet inserted it into the view hierarchy. This is achieved using the environmentObject() modifier, passing through the observable object instance as follows:

struct ContentView: View {
    let speedsetting = SpeedSetting()
 
    var body: some View {
        VStack {
            SpeedControlView()
            SpeedDisplayView()
        }
        .environmentObject(speedsetting)
    }
}

Once these steps have been taken the object will behave in the same way as an observed object, except that it will be accessible to all child views of the content view without having to be passed down through the view hierarchy. When the slider in SpeedControlView is moved, the Text view in SpeedDisplayView will update to reflect the current speed setting, thereby demonstrating that both views are accessing the same environment object:

Figure 22-1

Summary

SwiftUI provides three ways to bind data to the user interface and logic of an app. State properties are used to store the state of the views in a user interface layout and are local to the current content view. These transient values are lost when the view goes away.

For data that is external to the user interface and is required only by a subset of the SwiftUI view structures in an app, the observable object protocol should be used. Using this approach, the class or structure which represents the data must conform to the ObservableObject protocol and any properties to which views will bind must be declared using the @Published property wrapper. To bind to an observable object property in a view declaration the property must use the @ObservedObject or @StateObject property wrapper (@StateObject being the preferred option in the majority of cases).

For data that is external to the user interface, but for which access is required for many views, the environment object provides the best solution. Although declared in the same way as observable objects, environment object bindings are declared in SwiftUI View files using the @EnvironmentObject property wrapper. Before becoming accessible to child views, the environment object must also be initialized before being inserted into the view hierarchy using the environmentObject() modifier.

SwiftUI Stacks and Frames

User interface design is largely a matter of selecting the appropriate interface components, deciding how those views will be positioned on the screen, and then implementing navigation between the different screens and views of the app.

As is to be expected, SwiftUI includes a wide range of user interface components to be used when developing an app such as button, label, slider and toggle views. SwiftUI also provides a set of layout views for the purpose of defining both how the user interface is organized and the way in which the layout responds to changes in screen orientation and size.

This chapter will introduce the Stack container views included with SwiftUI and explain how they can be used to create user interface designs with relative ease.

Once stack views have been explained, this chapter will cover the concept of flexible frames and explain how they can be used to control the sizing behavior of views in a layout.

SwiftUI Stacks

SwiftUI includes three stack layout views in the form of VStack (vertical), HStack (horizontal) and ZStack (views are layered on top of each other).

A stack is declared by embedding child views into a stack view within the SwiftUI View file. In the following view, for example, three Image views have been embedded within an HStack:

struct ContentView: View {
    var body: some View {
        HStack {
            Image(systemName: "goforward.10")
            Image(systemName: "goforward.15")
            Image(systemName: "goforward.30")
        }
    }
}

Within the preview canvas, the above layout will appear as illustrated in Figure 21-1:

Figure 21-1

A similarly configured example using a VStack would accomplish the same results with the images stacked vertically:

VStack {
    Image(systemName: "goforward.10")
    Image(systemName: "goforward.15")
    Image(systemName: "goforward.30")
}

To embed an existing component into a stack, either wrap it manually within a stack declaration, or hover the mouse pointer over the component in the editor so that it highlights, hold down the Command key on the keyboard and left-click on the component. From the resulting menu (Figure 21-2) select the appropriate option:

Figure 21-2

Layouts of considerable complexity can be designed simply by embedding stacks within other stacks, for example:

VStack {
    Text("Financial Results")
        .font(.title)
    
    HStack {
        Text("Q1 Sales")
            .font(.headline)
        
        VStack {
            Text("January")
            Text("February")
            Text("March")
        }
        
        VStack {
            Text("$1000")
            Text("$200")
            Text("$3000")
        }
    }
}

The above layout will appear as shown in Figure 21-3:

Figure 21-3

As currently configured the layout clearly needs some additional work, particularly in terms of alignment and spacing. The layout can be improved in this regard using a combination of alignment settings, the Spacer component and the padding modifier.

Spacers, Alignment and Padding

To add space between views, SwiftUI includes the Spacer component. When used in a stack layout, the spacer will flexibly expand and contract along the axis of the containing stack (in other words either horizontally or vertically) to provide a gap between views positioned on either side, for example:

HStack(alignment: .top) {
 
    Text("Q1 Sales")
        .font(.headline)
    Spacer()
    VStack(alignment: .leading) {
        Text("January")
        Text("February")
        Text("March")
    }
    Spacer()
.
.

In terms of aligning the content of a stack, this can be achieved by specifying an alignment value when the stack is declared, for example:

VStack(alignment: .center) {
            Text("Financial Results")
                .font(.title)

Alignments may also be specified with a corresponding spacing value:

VStack(alignment: .center, spacing: 15) {
            Text("Financial Results")
                .font(.title)

Spacing around the sides of any view may also be implemented using the padding() modifier. When called without a parameter SwiftUI will automatically use the best padding for the layout, content and screen size (referred to as adaptable padding). The following example sets adaptable padding on all four sides of a Text view:

Text("Hello, world!")
    .padding()

Alternatively, a specific amount of padding may be passed as a parameter to the modifier as follows:

Text("Hello, world!")
    .padding(15)

Padding may also be applied to a specific side of a view with or without a specific value. In the following example a specific padding size is applied to the top edge of a Text view:

Text("Hello, world!")
    .padding(.top, 10)

Making use of these options, the example layout created earlier in the chapter can be modified as follows:

VStack(alignment: .center, spacing: 15) {
        Text("Financial Results")
            .font(.title)
    
        HStack(alignment: .top) {
            Text("Q1 Sales")
                .font(.headline)
            Spacer()
            VStack(alignment: .leading) {
                Text("January")
                Text("February")
                Text("March")
            }
            Spacer()
            VStack(alignment: .leading) {
                Text("$10000")
                Text("$200")
                Text("$3000")
            }
            .padding(5)
        }
        .padding(5)
    }
    .padding(5)
}

With the alignments, spacers and padding modifiers added, the layout should now resemble the following figure:

Figure 21-4

More advanced stack alignment topics will be covered in a later chapter entitled “SwiftUI Stack Alignment and Alignment Guides”.

Container Child Limit

Container views are limited to 10 direct descendant views. If a stack contains more than 10 direct children, Xcode will likely display the following syntax error:

Extra arguments at positions #11, #12 in call

If a stack exceeds the 10 direct children limit, the views will need to be embedded into multiple containers. This can, of course, be achieved by adding stacks as subviews, but another useful container is the Group view. In the following example, a VStack can contain 12 Text views by splitting the views between Group containers giving the VStack only two direct descendants:

VStack {
    
    Group {
         Text("Sample Text")
         Text("Sample Text")
         Text("Sample Text")
         Text("Sample Text")
         Text("Sample Text")
         Text("Sample Text")
    }
 
    Group {
         Text("Sample Text")
         Text("Sample Text")
         Text("Sample Text")
         Text("Sample Text")
         Text("Sample Text")
         Text("Sample Text")
    }
}

In addition to providing a way to avoid the 10-view limit, groups are also useful when performing an operation on multiple views (for example, a set of related views can all be hidden in a single operation by embedding them in a Group and hiding that view).

Text Line Limits and Layout Priority

By default, an HStack will attempt to display the text within its Text view children on a single line. Take, for example, the following HStack declaration containing an Image view and two Text views:

HStack {
    Image(systemName: "airplane")
    Text("Flight times:")
    Text("London")
}
.font(.largeTitle)

If the stack has enough room, the above layout will appear as follows:

Figure 21-5

If a stack has insufficient room (for example if it is constrained by a frame or is competing for space with sibling views) the text will automatically wrap onto multiple lines when necessary:

Figure 21-6

While this may work for some situations, it may become an issue if the user interface is required to display this text in a single line. The number of lines over which text can flow can be restricted using the lineCount() modifier. The example HStack could, therefore, be limited to 1 line of text with the following change:

HStack {
    Image(systemName: "airplane")
    Text("Flight times:") 
    Text("London")
}
.font(.largeTitle)
.lineLimit(1)

When an HStack has insufficient space to display the full text and is not permitted to wrap the text over enough lines, the view will resort to truncating the text, as is the case in Figure 21-7:

Figure 21-7

In the absence of any priority guidance, the stack view will decide how to truncate the Text views based on the available space and the length of the views. Obviously, the stack has no way of knowing whether the text in one view is more important than the text in another unless the text view declarations include some priority information. This is achieved by making use of the layoutPriority() modifier. This modifier can be added to the views in the stack and passed values indicating the level of priority for the corresponding view. The higher the number, the greater the layout priority and the less the view will be subjected to truncation.

Assuming the flight destination city name is more important than the “Flight times:” text, the example stack could be modified as follows:

HStack {
    Image(systemName: "airplane")
    Text("Flight times:")
    Text("London")
        .layoutPriority(1)
}
.font(.largeTitle)
.lineLimit(1)

With a higher priority assigned to the city Text view (in the absence of a layout priority the other text view defaults to a priority of 0) the layout will now appear as illustrated in Figure 21-8:

Figure 21-8

Traditional vs. Lazy Stacks

So far in this chapter we have only covered the HStack, VStack and ZStack views. Although the stack examples shown so far contain relatively few child views, it is possible for a stack to contain large quantities of views. This is particularly common when a stack is embedded in a ScrollView. ScrollView is a view which allows the user to scroll through content that extends beyond the visible area of either the containing view or device the screen.

When using the traditional HStack and VStack views, the system will create all the views child views at initialization, regardless of whether those views are currently visible to the user. While this may not be an issue for most requirements, this can lead to performance degradation in situations where a stack has thousands of child views.

To address this issue, SwiftUI also provides “lazy” vertical and horizontal stack views. These views (named LazyVStack and LazyHStack) use exactly the same declaration syntax as the traditional stack views, but are designed to only create child views as they are needed. For example, as the user scrolls through a stack, views that are currently off screen will only be created once they approach the point of becoming visible to the user. Once those views pass out of the viewing area, SwiftUI releases those views so that they no longer take up system resources.

When deciding whether to use traditional or lazy stacks, it is generally recommended to start out using the traditional stacks and to switch to lazy stacks if you encounter performance issues relating to a high number of child views.

SwiftUI Frames

By default, a view will be sized automatically based on its content and the requirements of any layout in which it may be embedded. Although much can be achieved using the stack layouts to control the size and positioning of a view, sometimes a view is required to be a specific size or to fit within a range of size dimensions. To address this need, SwiftUI includes the flexible frame modifier.

Consider the following Text view which has been modified to display a border:

Text("Hello World")
    .font(.largeTitle)
    .border(Color.black)

Within the preview canvas, the above text view will appear as follows:

Figure 21-9

In the absence of a frame, the text view has been sized to accommodate its content. If the Text view was required to have height and width dimensions of 100, however, a frame could be applied as follows:

Text("Hello World")
    .font(.largeTitle)
    .border(Color.black)
    .frame(width: 100, height: 100, alignment: .center)

Now that the Text view is constrained within a frame, the view will appear as follows:

Figure 21-10

In many cases, fixed dimensions will provide the required behavior. In other cases, such as when the content of a view changes dynamically, this can cause problems. Increasing the length of the text, for example, might cause the content to be truncated:

Figure 21-11

This can be resolved by creating a frame with minimum and maximum dimensions:

Text("Hello World, how are you?")
            .font(.largeTitle)
            .border(Color.black)
            .frame(minWidth: 100, maxWidth: 300, minHeight: 100, 
                   maxHeight: 100, alignment: .center)

Now that the frame has some flexibility, the view will be sized to accommodate the content within the defined minimum and maximum limits. When the text is short enough, the view will appear as shown in Figure 21-10 above. Longer text, however, will be displayed as follows:

Figure 21-12

Frames may also be configured to take up all the available space by setting the minimum and maximum values to 0 and infinity respectively:

.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, 
          maxHeight: .infinity)

Remember that the order in which modifiers are chained often impacts the appearance of a view. In this case, if the border is to be drawn at the edges of the available space it will need to be applied to the frame:

Text("Hello World, how are you?")
    .font(.largeTitle)
    .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, 
          maxHeight: .infinity)
    .border(Color.black, width: 5)

By default, the frame will honor the safe areas on the screen when filling the display. Areas considered to be outside the safe area include those occupied by the camera notch on some device models and the bar across the top of the screen displaying the time and Wi-Fi and cellular signal strength icons. To configure the frame to extend beyond the safe area, simply use the edgesIgnoringSafeArea() modifier, specifying the safe area edges to ignore:

.edgesIgnoringSafeArea(.all)

Frames and the Geometry Reader

Frames can also be implemented so that they are sized relative to the size of the container within which the corresponding view is embedded. This is achieved by wrapping the view in a GeometryReader and using the reader to identify the container dimensions. These dimensions can then be used to calculate the frame size. The following example uses a frame to set the dimensions of two Text views relative to the size of the containing VStack:

GeometryReader { geometry in
    VStack {
        Text("Hello World, how are you?")
            .font(.largeTitle)
            .frame(width: geometry.size.width / 2, 
                height: (geometry.size.height / 4) * 3)
        Text("Goodbye World")
            .font(.largeTitle)
            .frame(width: geometry.size.width / 3, 
                height: geometry.size.height / 4)
    }
}

The topmost Text view is configured to occupy half the width and three quarters of the height of the VStack while the lower Text view occupies one third of the width and one quarter of the height.

Summary

User interface design mostly involves gathering components and laying them out on the screen in a way that provides a pleasant and intuitive user experience. User interface layouts must also be responsive so that they appear correctly on any device regardless of screen size and, ideally, device orientation. To ease the process of user interface layout design, SwiftUI provides several layout views and components. In this chapter we have looked at layout stack views and the flexible frame.

By default, a view will be sized according to its content and the restrictions imposed on it by any view in which it may be contained. When insufficient space is available, a view may be restricted in size resulting in truncated content. Priority settings can be used to control the amount by which views are reduced in size relative to container sibling views.

For greater control of the space allocated to a view, a flexible frame can be applied to the view. The frame can be fixed in size, constrained within a range of minimum and maximum values or, using a Geometry Reader, sized relative to the containing view.

Creating Custom Views with SwiftUI

A key step in learning to develop apps using SwiftUI is learning how to declare user interface layouts both by making use of the built-in SwiftUI views as well as building your own custom views. This chapter will introduce the basic concepts of SwiftUI views and outline the syntax used to declare user interface layouts and modify view appearance and behavior.

SwiftUI Views

User interface layouts are composed in SwiftUI by using, creating and combining views. An important first step is to understand what is meant by the term “view”. Views in SwiftUI are declared as structures that conform to the View protocol. In order to conform with the View protocol, a structure is required to contain a body property and it is within this body property that the view is declared.

SwiftUI includes a wide range of built-in views that can be used when constructing a user interface including text label, button, text field, menu, toggle and layout manager views. Each of these is a self-contained instance that complies with the View protocol. When building an app with SwiftUI you will use these views to create custom views of your own which, when combined, constitute the appearance and behavior of your user interface.

These custom views will range from subviews that encapsulate a reusable subset of view components (perhaps a secure text field and a button for logging in to screens within your app) to views that encapsulate the user interface for an entire screen. Regardless of the size and complexity of a custom view or the number of child views encapsulated within, a view is still just an instance that defines some user interface appearance and behavior.

Creating a Basic View

In Xcode, custom views are contained within SwiftUI View files. When a new SwiftUI project is created, Xcode will create a single SwiftUI View file containing a single custom view consisting of a single Text view component. Additional view files can be added to the project by selecting the File -> New -> File… menu option and choosing the SwiftUI View file entry from the template screen.

The default SwiftUI View file is named ContentView.swift and reads as follows:

import SwiftUI
 
struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .padding()
    }
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

The view is named ContentView and is declared as conforming to the View protocol. It also includes the mandatory body property which, in turn contains an instance of the built-in Text view component which is initialized with a string which reads “Hello, world!”.

The second structure in the file is needed to create an instance of ContentView so that it appears in the preview canvas, a topic which will be covered in detail in later chapters.

Adding Additional Views

Additional views can be added to a parent view by placing them in the body. The body property, however, is configured to return a single view. Adding an additional view, as is the case in the following example, will cause Xcode to create a second preview containing just the “Goodbye, world!” text view:

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .padding()
        Text("Goodbye, world!")
    }
}

To correctly add additional views, those views must be placed in a container view such as a stack or form. The above example could, therefore, be modified to place the two Text views in a vertical stack (VStack) view which, as the name suggests, positions views vertically within the containing view:

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, world!")
                .padding()
            Text("Goodbye, world!")
        }
    }
}

SwiftUI views are hierarchical by nature, starting with parent and child views. This allows views to be nested to multiple levels to create user interfaces of any level of complexity. Consider, for example, the following view hierarchy diagram:

Figure 20-1

The equivalent view declaration for the above view would read as follows:

struct ContentView: View {
    var body: some View {
        VStack {
            VStack {
                Text("Text 1")
                Text("Text 2")
                HStack {
                    Text("Text 3")
                    Text("Text 4")
                }
            }
            Text("Text 5")
        }
    }
}

A notable exception to the requirement that multiple views be embedded in a container is that multiple Text views count as a single view when concatenated. The following, therefore, is a valid view declaration:

struct ContentView: View {
    var body: some View {
        Text("Hello, ") + Text("how ") + Text("are you?")
    }
}

Note that in the above examples the closure for the body property does not have a return statement. This is because the closure essentially contains a single expression (implicit returns from single expressions were covered in the chapter entitled “Swift Functions, Methods and Closures”). As soon as extra expressions are added to the closure, however, it will be necessary to add a return statement, for example:

struct ContentView: View {
    var body: some View {
 
    var myString: String = "Welcome to SwiftUI"
        
    return VStack {
            Text("Hello, world!")
                .padding()
            Text("Goodbye, world")
        }
    }
}

Working with Subviews

Apple recommends that views be kept as small and lightweight as possible. This promotes the creation of reusable components, makes view declarations easier to maintain and results in more efficient layout rendering.

If you find that a custom view declaration has become large and complex, identify areas of the view that can be extracted into a subview. As a very simplistic example, the HStack view in the above example could be extracted as a subview named “MyHStackView” as follows:

struct ContentView: View {
    var body: some View {
        VStack {
            VStack {
                Text("Text 1")
                Text("Text 2")
                MyHStackView()
            }
            Text("Text 5")
        }
    }
}
 
struct MyHStackView: View {
    var body: some View {
        HStack {
            Text("Text 3")
            Text("Text 4")
        }
    }
}

Views as Properties

In addition to creating subviews, views may also be assigned to properties as a way to organize complex view hierarchies. Consider the following example view declaration:

struct ContentView: View {
    
    var body: some View {
        
        VStack {
            Text("Main Title")
                .font(.largeTitle)
            HStack {
                Text("Car Image")
                Image(systemName: "car.fill")
            }
        }
    }
}

Any part of the above declaration can be moved to a property value, and then referenced by name. In the following declaration, the HStack has been assigned to a property named carStack which is then referenced within the VStack layout:

struct ContentView: View {
    
    let carStack = HStack {
        Text("Car Image")
        Image(systemName: "car.fill")
    }
    
    var body: some View {
        VStack {
            Text("Main Title")
                .font(.largeTitle)
            carStack
        }
    }
}

Modifying Views

It is unlikely that any of the views provided with SwiftUI will appear and behave exactly as required without some form of customization. These changes are made by applying modifiers to the views.

All SwiftUI views have sets of modifiers which can be applied to make appearance and behavior changes. These modifiers take the form of methods that are called on the instance of the view and essentially wrap the original view inside another view which applies the necessary changes. This means that modifiers can be chained together to apply multiple modifications to the same view. The following, for example, changes the font and foreground color of a Text view:

Text("Text 1")
    .font(.headline)
    .foregroundColor(.red)

Similarly, the following example uses modifiers to configure an Image view to be resizable with the aspect ratio set to fit proportionally within the available space:

Image(systemName: "car.fill")
    .resizable()
    .aspectRatio(contentMode: .fit)

Modifiers may also be applied to custom subviews. In the following example, the font for both Text views in the previously declared MyHStackView custom view will be changed to use the large title font style:

MyHStackView()
    .font(.largeTitle)

Working with Text Styles

In the above example the font used to display text on a view was declared using a built-in text style (in this case the large title style).

iOS provides a way for the user to select a preferred text size which applications are expected to adopt when displaying text. The current text size can be configured on a device via the Settings -> Display & Brightness -> Text Size screen which provides a slider to adjust the font size as shown below:

Figure 20-2

If a font has been declared on a view using a text style, the text size will dynamically adapt to the user’s preferred font size. Almost without exception, the built-in iOS apps adopt the preferred size setting selected by the user when displaying text and Apple recommends that third-party apps also conform to the user’s chosen text size. The following text style options are currently available:

  • Large Title
  • Title, Title2, Title 3
  • Headline
  • Subheadline
  • Body
  • Callout
  • Footnote
  • Caption1, Caption2

If none of the text styles meet your requirements, it is also possible to apply custom fonts by declaring the font family and size. Although the font size is specified in the custom font, the text will still automatically resize based on the user’s preferred dynamic type text size selection:

Text("Sample Text")
    .font(.custom("Copperplate", size: 70)) 

The above custom font selection will render the Text view as follows:

Figure 20-3

Modifier Ordering

When chaining modifiers, it is important to be aware that the order in which they are applied can be significant. Both border and padding modifiers have been applied to the following Text view.

Text("Sample Text")
    .border(Color.black)
    .padding()

The border modifier draws a black border around the view and the padding modifier adds space around the view. When the above view is rendered it will appear as shown in Figure 20-4:

Figure 20-4

Given that padding has been applied to the text, it might be reasonable to expect there to be a gap between the text and the border. In fact, the border was only applied to the original Text view. Padding was then applied to the modified view returned by the border modifier. The padding is still applied to the view, but outside of the border. For the border to encompass the padding, the order of the modifiers needs to be changed so that the border is drawn on the view returned by the padding modifier:

Text("Sample Text")
    .padding()
    .border(Color.black)

With the modifier order switched, the view will now be rendered as follows:

Figure 20-5

If you don’t see the expected effects when working with chained modifiers, keep in mind this may be because of the order in which they are being applied to the view.

Custom Modifiers

SwiftUI also allows you to create your own custom modifiers. This can be particularly useful if you have a standard set of modifiers that are frequently applied to views. Suppose that the following modifiers are a common requirement within your view declarations:

Text("Text 1")
    .font(.largeTitle)
    .background(Color.white)
    .border(Color.gray, width: 0.2)
    .shadow(color: Color.black, radius: 5, x: 0, y: 5)

Instead of applying these four modifiers each time text with this appearance is required, a better solution is to group them into a custom modifier and then reference that modifier each time the modification is needed. Custom modifiers are declared as structs that conform to the ViewModifier protocol and, in this instance, might be implemented as follows:

struct StandardTitle: ViewModifier {
   func body(content: Content) -> some View {
        content
            .font(.largeTitle)
            .background(Color.white)
            .border(Color.gray, width: 0.2)
            .shadow(color: Color.black, radius: 5, x: 0, y: 5)
    }
}

The custom modifier is then applied when needed by passing it through to the modifier() method:

Text("Text 1")
    .modifier(StandardTitle())
Text("Text 2")
    .modifier(StandardTitle())

With the custom modifier implemented, changes can be made to the StandardTitle implementation and those changes will automatically propagate through to all views that use the modifier. This avoids the need to manually change the modifiers on multiple views.

Basic Event Handling

Although SwiftUI is described as being data driven, it is still necessary to handle the events that are generated when a user interacts with the views in the user interface. Some views, such as the Button view, are provided solely for the purpose of soliciting user interaction. In fact, the Button view can be used to turn a variety of different views into a “clickable” button. A Button view needs to be declared with the action method to be called when a click is detected together with the view to act as the button content. It is possible, for example, to designate an entire stack of views as a single button. In most cases, however, a Text view will typically be used as the Button content. In the following implementation, a Button view is used to wrap a Text view which, when clicked, will call a method named buttonPressed():

struct ContentView: View {
    var body: some View {
        Button(action: buttonPressed) {
            Text("Click Me")
        }
    }
    
    func buttonPressed() {
        // Code to perform action here
    } 
}

Instead of specifying an action function, the code to be executed when the button is clicked may also be specified as a closure in-line with the declaration:

Button(action: {
    // Code to perform action here
}) {
    Text("Click Me")
}

Another common requirement is to turn an Image view into a button, for example:

Button(action: {
    print("Button clicked")
}) {
    Image(systemName: "square.and.arrow.down")
}

Building Custom Container Views

As outlined earlier in this chapter, subviews provide a useful way to divide a view declaration into small, lightweight and reusable blocks. One limitation of subviews, however, is that the content of the container view is static. In other words, it is not possible to dynamically specify the views that are to be included at the point that a subview is included in a layout. The only children included in the subview are those that are specified in the original declaration.

Consider the following subview which consists of three TextViews contained within a VStack and modified with custom spacing and font settings.

struct MyVStack: View {
    var body: some View {
        VStack(spacing: 10) {
            Text("Text Item 1")
            Text("Text Item 2")
            Text("Text Item 3")
        }
        .font(.largeTitle)
    }
}

To include an instance of MyVStack in a declaration, it would be referenced as follows:

MyVStack()

Suppose, however, that a VStack with a spacing of 10 and a large font modifier is something that is needed frequently within a project, but in each case, different child views are required to be contained within the stack. While this flexibility isn’t possible using subviews, it can be achieved using the SwiftUI ViewBuilder closure attribute when constructing custom container views.

A ViewBuilder takes the form of a Swift closure which can be used to create a custom view comprised of multiple child views, the content of which does not need to be declared until the view is used within a layout declaration. The ViewBuilder closure takes the content views and returns them as a single view which is, in effect, a dynamically built subview.

The following is an example of using the ViewBuilder attribute to implement our custom MyVStack view:

struct MyVStack<Content: View>: View {
  let content: () -> Content
  init(@ViewBuilder content: @escaping () -> Content) {
    self.content = content
  }
 
  var body: some View {
    VStack(spacing: 10) {
      content()
   }
   .font(.largeTitle)
  }
}

Note that this declaration still returns an instance that complies with the View protocol and that the body contains the VStack declaration from the previous subview. Instead of including static views to be included in the stack, however, the child views of the stack will be passed to the initializer, handled by ViewBuilder and embedded into the VStack as child views. The custom MyVStack view can now be initialized with different child views wherever it is used in a layout, for example:

MyVStack {
    Text("Text 1")
    Text("Text 2")
    HStack {
        Image(systemName: "star.fill")
        Image(systemName: "star.fill")
        Image(systemName: "star")
    }
}

Working with the Label View

The Label view is different from most other SwiftUI views in that it comprises two elements in the form of an icon and text positioned side-by-side. The image can take the form of any image asset, a SwiftUI Shape rendering or an SF Symbol.

SF Symbols is a collection of over 1500 scalable vector drawings available for use when developing apps for Apple platforms and designed to complement Apple’s San Francisco system font.

The full set of symbols can be searched and browsed by installing the SF Symbols macOS app available from the following URL:

https://developer.apple.com/design/downloads/SF-Symbols.dmg

The following is an example of the Label view using an SF Symbol together with a font() modifier to increase the size of the icon and text:

Label("Welcome to SwiftUI", systemImage: "person.circle.fill")
    .font(.largeTitle)

The above view will be rendered as shown in Figure 20-6 below:

Figure 20-6

By referencing systemImage: in the Label view declaration we are indicating that the icon is to be taken from the built-in SF Symbol collection. To display an image from the app’s asset catalog, the following syntax would be used instead:

Label("Welcome to SwiftUI", image: "myimage")

Instead of specifying a text string and an image, the Label may also be declared using separate views for the title and icon. The following Label view declaration, for example, uses a Text view for the title and a Circle drawing for the icon:

Label(
    title: {
        Text("Welcome to SwiftUI")
        .font(.largeTitle)
    },
    icon: { Circle()
        .fill(Color.blue)
        .frame(width: 25, height: 25)
    }
)

When rendered, the above Label view will appear as shown in Figure 20-7:

Figure 20-7

Summary

SwiftUI user interfaces are declared in SwiftUI View files and are composed of components that conform to the View protocol. To conform with the View protocol a structure must contain a property named body which is itself a View.

SwiftUI provides a library of built-in components for use when designing user interface layouts. The appearance and behavior of a view can be configured by applying modifiers, and views can be modified and grouped together to create custom views and subviews. Similarly, custom container views can be created using the ViewBuilder closure property.

When a modifier is applied to a view, a new modified view is returned and subsequent modifiers are then applied to this modified view. This can have significant implications for the order in which modifiers are applied to a view.

The Anatomy of a Basic SwiftUI Project

When a new SwiftUI project is created in Xcode using the Multiplatform App template, Xcode generates a number of different files and folders which form the basis of the project, and on which the finished app will eventually be built.

Although it is not necessary to know in detail about the purpose of each of these files when beginning with SwiftUI development, each of them will become useful as you progress to developing more complex applications. This chapter will provide a brief overview of each element of a basic Xcode project structure.

Creating an Example Project

If you have not already done so, it may be useful to create a sample project to review while working through this chapter. To do so, launch Xcode and, on the welcome screen, select the option to create a new project. On the resulting template selection panel, select the Multiplatform tab followed by the App option before proceeding to the next screen:

Figure 19-1

On the project options screen, name the project DemoProject. Click Next to proceed to the final screen, choose a suitable filesystem location for the project and click on the Create button.

Project Folders

SwiftUI is intended to allow apps to be developed which can, with minimal modification, run on a variety of Apple platforms including iOS, iPadOS, watchOS, tvOS and macOS. In a typical multiplatform project, there will be a mixture of code that is shared by all platforms and code which is specific to an operating system. In recognition of this, Xcode structures the project with a folder for the shared code and files together with folders to hold the code and files specific to macOS as shown in Figure 19-2. Additional folders may be added in which to place iPadOS, watchOS and tvOS specific code if needed:

Figure 19-2

The DemoProjectApp.swift File

The DemoProjectApp.swift file contains the declaration for the App object as described in the chapter entitled SwiftUI Architecture and will read as follows:

import SwiftUI
 
@main
struct DemoProjectApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

As implemented, the declaration returns a Scene consisting of a WindowGroup containing the View defined in the ContentView.swift file. Note that the declaration is prefixed with @main. This indicates to SwiftUI that this is the entry point for the app when it is launched on a device.

The ContentView.swift File

This is a SwiftUI View file that, by default, contains the content of the first screen to appear when the app starts. This file and others like it are where most of the work is performed when developing apps in SwiftUI. By default, it contains a single Text view displaying the words “Hello, world!”:

import SwiftUI
 
struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .padding()
    }
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Assets.xcassets

The Assets.xcassets folder contains the asset catalog that is used to store resources used by the app such as images, icons and colors.

Summary

When a new SwiftUI project is created in Xcode using the Multiplatform App template, Xcode automatically generates a number of files required for the app to function. All of these files and folders can be modified to add functionality to the app, both in terms of adding resource assets, performing initialization and de-initialization tasks and building the user interface and logic of the app. Folders are used to provide a separation between code that is common to all operating systems and platform specific code.

131

SwiftUI Architecture

A completed SwiftUI app is constructed from multiple components which are assembled in a hierarchical manner. Before embarking on the creation of even the most basic of SwiftUI projects, it is useful to first gain an understanding of how SwiftUI apps are structured. With this goal in mind, this chapter will introduce the key elements of SwiftUI app architecture, with an emphasis on App, Scene and View elements.

SwiftUI App Hierarchy

When considering the structure of a SwiftUI application, it helps to view a typical hierarchy visually. Figure 18-1, for example, illustrates the hierarchy of a simple SwiftUI app:

Figure 18-1

Before continuing, it is important to distinguish the difference between the term “app” and the “App” element outlined in the above figure. The software applications that we install and run on our mobile devices have come to be referred to as “apps”. In this chapter reference will be made both to these apps and the App element in the above figure. To avoid confusion, we will use the term “application” to refer to the completed, installed and running app, while referring to the App element as “App”. The remainder of the book will revert to using the more common “app” when talking about applications.

App

The App object is the top-level element within the structure of a SwiftUI application and is responsible for handling the launching and lifecycle of each running instance of the application.

The App element is also responsible for managing the various Scenes that make up the user interface of the application. An application will include only one App instance.

Scenes

Each SwiftUI application will contain one or more scenes. A scene represents a section or region of the application’s user interface. On iOS and watchOS a scene will typically take the form of a window which takes up the entire device screen. SwiftUI applications running on macOS and iPadOS, on the other hand, will likely be comprised of multiple scenes. Different scenes might, for example, contain context specific layouts to be displayed when tabs are selected by the user within a dialog, or to design applications that consist of multiple windows.

SwiftUI includes some pre-built primitive scene types that can be used when designing applications, the most common of which being WindowGroup and DocumentGroup. It is also possible to group scenes together to create your own custom scenes.

Views

Views are the basic building blocks that make up the visual elements of the user interface such as buttons, labels and text fields. Each scene will contain a hierarchy of the views that make up a section of the application’s user interface. Views can either be individual visual elements such as text views or buttons, or take the form of containers that manage other views. The Vertical Stack view, for example, is designed to display child views in a vertical layout. In addition to the Views provided with SwiftUI, you will also create custom views when developing SwiftUI applications. These custom views will comprise groups of other views together with customizations to the appearance and behavior of those views to meet the requirements of the application’s user interface.

Figure 18-2, for example, illustrates a scene containing a simple view hierarchy consisting of a Vertical Stack containing a Button and TextView combination:

Figure 18-2

Summary

SwiftUI applications are constructed hierarchically. At the top of the hierarchy is the App instance which is responsible for the launching and lifecycle of the application. One or more child Scene instances contain hierarchies of the View instances that make up the user interface of the application. These scenes can either be derived from one of the SwiftUI primitive Scene types such as WindowGroup, or custom built.

On iOS or watchOS, an application will typically contain a single scene which takes the form of a window occupying the entire display. On a macOS or iPadOS system, however, an application may comprise multiple scene instances, often represented by separate windows which can be displayed simultaneously or grouped together in a tabbed interface.

Using Xcode in SwiftUI Mode

When creating a new project, Xcode now provides a choice of creating either a Storyboard or SwiftUI-based user interface for the project. When creating a SwiftUI project, Xcode appears and behaves significantly differently when designing the user interface for an app project compared to the UIKit Storyboard mode.

When working in SwiftUI mode, most of your time as an app developer will be spent in the code editor and preview canvas, both of which will be explored in detail in this chapter.

Starting Xcode 13

As with all the examples in this book, the development of our example will take place within the Xcode 13.2 development environment. If you have not already installed this tool together with the latest iOS SDK refer first to the “Installing Xcode 13 and the iOS 15 SDK” chapter of this book. Assuming the installation is complete, launch Xcode either by clicking on the icon on the dock (assuming you created one) or use the macOS Finder to locate Xcode in the Applications folder of your system.

When launched for the first time, and until you turn off the Show this window when Xcode launches toggle, the screen illustrated in Figure 17-1 will appear by default:

Figure 17-1

If you do not see this window, simply select the Window -> Welcome to Xcode menu option to display it. From within this window, click on the option to Create a new Xcode project.

Creating a SwiftUI Project

When creating a new project, the project template screen includes options to select how the app project is to be implemented. Options are available to design an app for a specific Apple platform (such as iOS, watchOS, macOS, DriveKit, or tvOS), or to create a multiplatform project. Selecting a platform-specific option will also provide the choice of creating either a Storyboard (UIKit) or SwiftUI-based project.

A multiplatform project allows an app to be designed for multiple Apple platforms with the minimum of platform-specific code. Even if you plan to initially only target iOS the multiplatform option is still recommended since it provides the flexibility to make the app available on other platforms in the future without having to restructure the project.

Templates are also available for creating a basic app, a document-based app or a game project. For the purposes of this chapter, use the multiplatform app option:

Figure 17-2

Clicking Next will display the project options screen where the project name needs to be entered (in this case, name the project DemoProject).

The Organization Identifier is typically the reversed URL of your company’s website, for example “com. mycompany”. This will be used when creating provisioning profiles and certificates to enable testing of advanced features of iOS on physical devices. It also serves to uniquely identify the app within the Apple App Store when the app is published:

Figure 17-3

Click Next once again and choose a location on your filesystem in which to place the project before clicking on the Create button.

Once a new project has been created, the main Xcode panel will appear with the default layout for SwiftUI development displayed.

Xcode in SwiftUI Mode

Before beginning work on a SwiftUI user interface, it is worth taking some time to gain familiarity with how Xcode works in SwiftUI mode. A newly created multiplatform “app” project includes two SwiftUI View files named <app name>App.swift (in this case DemoProjectApp.swift) and ContentView.swift which, when selected from the project navigation panel, will appear within Xcode as shown in Figure 17-4 below:

Figure 17-4

Located to the right of the project navigator (A) is the code editor (B). To the right of this is the preview canvas (C) where any changes made to the SwiftUI layout declaration will appear in real-time.

Selecting a view in the canvas will automatically select and highlight the corresponding entry in the code editor, and vice versa. Attributes for the currently selected item will appear in the attributes inspector panel (D).

During debugging, the debug panel (E) will appear containing debug output from both the iOS frameworks and any diagnostic print statements you have included in your code. If the console is not currently visible, display it by clicking on the button indicated by the arrow in Figure 17-5:

Figure 17-5

The debug panel can be configured to show a variable view, a console view, or both views in a split panel arrangement. The variable view displays variables within the app at the point that the app crashes or reaches a debugging break point. The console view, on the other hand, displays print output and messages from the running app. Figure 17-6 shows both views displayed together with an arrow indicating the buttons used to hide and show the different views:

Figure 17-6

The button indicated in Figure 17-5 above may be used to hide the debug panel (E), while the two buttons highlighted in Figure 17-7 below hide and show the project navigator and inspector panels:

Figure 17-7

The tab bar (marked A above) displays a tab for each currently open file. When a tab is clicked, the corresponding file is loaded into the editor. Hovering the mouse pointer over a tab will display an “X” button within the tab which will close the file when clicked.

The area marked F in Figure 17-4 is called the minimap. This map provides a miniaturized outline of the source code in the editor. Particularly useful when working with large source files, the minimap panel provides a quick way to move to different areas of the code. Hovering the mouse pointer of a line in the minimap will display a label indicating the class, property or function at that location as illustrated in Figure 17-9:

Figure 17-8

Clicking either on the label or within the map will take you to that line in the code editor. Holding down the Command key while hovering will display all of the elements contained within the source file as shown in Figure 17-9:

Figure 17-9

The minimap can be displayed and hidden by toggling the Editor -> Minimap menu option.

The Preview Canvas

The preview canvas provides both a visual representation of the user interface design and a tool for adding and modifying views within the layout design. The canvas may also be used to perform live testing of the running app without the need to launch an iOS simulator. Figure 17-10 illustrates a typical preview canvas for a newly created project:

Figure 17-10

If the canvas is not visible it can be displayed using the Xcode Editor -> Canvas menu option.

The main canvas area (A) represents the current view as it will appear when running on a physical device. When changes are made to the code in the editor, those changes are reflected within the preview canvas. To avoid continually updating the canvas, and depending on the nature of the changes being made, the preview will occasionally pause live updates. When this happens, the Resume button will appear in the top right-hand corner of the preview panel which, when clicked, will once again begin updating the preview:

Figure 17-11

The size buttons (B) can be used to zoom in and out of the canvas.

Preview Pinning

When building an app in Xcode it is likely that it will consist of several SwiftUI View files in addition to the default ContentView.swift file. When a SwiftUI View file is selected from the project navigator, both the code editor and preview canvas will change to reflect the currently selected file. Sometimes you may want the user interface layout for one SwiftUI file to appear in the preview canvas while editing the code in a different file. This can be particularly useful if the layout from one file is dependent on or embedded in another view. The pin button (labeled C in Figure 17-10 above) pins the current preview to the canvas so that it remains visible on the canvas after navigating to a different view. The view to which you have navigated will appear beneath the pinned view in the canvas and can be scrolled into view.

The Preview Toolbar

The preview toolbar (marked D in Figure 17-10 above and shown below) provides a range of options for changing the preview panel:

Figure 17-12

By default, the preview displays a static representation of the user interface. To test the user interface in a running version of the app, simply click on the Live Preview button (A). Xcode will then build the app and run it within the preview canvas where you can interact with it as you would in a simulator or on a physical device. When in Live Preview mode, the button changes to a stop button which can be used to exit live mode.

The current version of the app may also be previewed on an attached physical device by clicking on the Preview on Device button (B). As with the preview canvas, the running app on the device will update dynamically as changes are made to the code in the editor. Click the button marked C to rotate the preview between portrait and landscape modes.

The Inspect Preview button (D) displays the panel shown in Figure 17-13 below allowing properties of the canvas to be changed such as the device type, color scheme (light or dark mode) and dynamic text size.

Figure 17-13

The Duplicate Preview button (E) allows multiple preview canvases to be displayed simultaneously (a topic that will be covered later in this chapter).

Modifying the Design

Working with SwiftUI primarily involves adding additional views, customizing those views using modifiers, adding logic and interacting with state and other data instance bindings. All of these tasks can be performed exclusively by modifying the structure in the code editor. The font used to display the “Hello, world!” Text view, for example, can be changed by adding the appropriate modifier in the editor:

Text("Hello, world!")
    .padding()
    .font(.largeTitle)

An alternative to this is to make changes to the SwiftUI views by dragging and dropping items from the Library panel. The Library panel is displayed by clicking on the toolbar button highlighted in Figure 17-14:

Figure 17-14

When displayed, the Library panel will appear as shown in Figure 17-15:

Figure 17-15

When launched in this way, the Library panel is transient and will disappear either after a selection has been made, or a click is performed outside of the panel. To keep the panel displayed, hold down the Option key when clicking on the Library button.

When first opened, the panel displays a list of views available for inclusion in the user interface design. The list can be browsed, or the search bar used to narrow the list to specific views. The toolbar (highlighted in the above figure) can be used to switch to other categories such as modifiers, commonly used code snippets, images and color resources.

An item within the library can be applied to the user interface design in a number of ways. To apply a font modifier to the “Hello, world!” Text view, one option is to select the view in either the code or preview canvas, locate the font modifier in the Library panel, and double-click on it. Xcode will then automatically apply the font modifier.

Another option is to locate the Library item and then drag and drop it onto the desired location either in the code editor or the preview canvas. In Figure 17-16 below, for example, the font modifier is being dragged to the Text view within the editor:

Figure 17-16

The same result can be achieved by dragging an item from the library onto the preview canvas. In the case of Figure 17-17, a Button view is being added to the layout beneath the existing Text view:

Figure 17-17

In this example, the side along which the view will be placed if released highlights and the preview canvas displays a notification that the Button and existing Text view will automatically be placed in a Vertical Stack container view (stacks will be covered later in the chapter entitled SwiftUI Stacks and Frames).

Once a view or modifier has been added to the SwiftUI view file it is highly likely that some customization will be necessary, such as specifying the color for a foreground modifier. One option is, of course, to simply make the changes within the editor, for example:

Text("Hello, world!")
    .padding()
    .font(.largeTitle)
    .foregroundColor(.red)

Another option is to select the view in either the editor or preview panel and then make the necessary changes within the Attributes inspector panel:

Figure 17-18

The Attributes inspector will provide the option to make changes to any modifiers already applied to the selected view.

Before moving on to the next topic, it is also worth noting that the Attributes inspector provides yet another way to add modifiers to a view via the Add Modifier menu located at the bottom of the panel. When clicked, this menu will display a long list of modifiers available for the current view type. To apply a modifier, simply select it from the menu. An entry for the new modifier will subsequently appear in the inspector where it can be configured with the required properties.

Editor Context Menu

Holding down the Command key while clicking on an item in the code editor will display the menu shown in Figure 17-19:

Figure 17-19

This menu provides a list of options that will vary depending on the type of item selected. Options typically include a shortcut to a popup version of the Attributes inspector for the current view, together with options to embed the current view in a stack or list container. This menu is also useful for extracting part of a view into its own self-contained subview. Creating subviews is strongly encouraged to promote reuse, improve performance and unclutter complex design structures.

Previewing on Multiple Device Configurations

Every newly created SwiftUI View file includes an additional declaration at the bottom of the file that resembles the following:

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

This structure, which conforms to the PreviewProvider protocol, returns an instance of the primary view within the file. This instructs Xcode to display the preview for that view within the preview canvas (without this declaration, nothing will appear in the canvas).

By default, the preview canvas shows the user interface on a single device based on the current selection in the run target menu to the right of the run and stop buttons in the Xcode toolbar (as highlighted in Figure 1721 below). To preview on other device models, one option is to simply change the run target and wait for the preview canvas to change.

A better option, however, is to modify the previews structure to specify a different device. In the following example, the canvas previews the user interface on an iPhone SE:

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .previewDevice("iPhone SE (2nd generation)")
            .previewDisplayName("iPhone SE")
    }
}

In fact, it is possible using this technique to preview multiple device types simultaneously by placing them into a Group view as follows:

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        
        Group {
            ContentView()
                .previewDevice("iPhone 11")
                .previewDisplayName("iPhone 11")
            ContentView()
                .previewDevice("iPhone SE (2nd generation)")
                .previewDisplayName("iPhone SE")
        }
    }
}

When multiple devices are previewed, they appear in a scrollable list within the preview canvas as shown in Figure 17-20:

Figure 17-20

The environment modifier may also be used to preview the layout in other configurations, for example, to preview in dark mode:

ContentView()
    .preferredColorScheme(.dark)
    .previewDevice("iPhone SE (2nd generation)")

This preview structure is also useful for passing sample data into the enclosing view for testing purposes within the preview canvas, a technique that will be used in later chapters. For example:

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(sampleData: mySampleData)                 
    }
}

An alternative to manually editing the PreviewProvider declaration is to simply duplicate the current preview instance using the Duplicate Preview button marked D in Figure 17-12 above. Once the new preview appears, it will have its own preview toolbar within which the Preview Inspect button (C) may be used to configure the properties of the preview. All of these changes will automatically be reflected in the PreviewProvider declaration within the view file.

Running the App on a Simulator

Although much can be achieved using the preview canvas, there is no substitute for running the app on physical devices and simulators during testing.

Within the main Xcode project window, the menu marked C in Figure 17-21 is used to choose a target simulator. This menu will include simulators that have been configured and any physical devices connected to the development system:

Figure 17-21

When a project is first created, it may initially be configured to target macOS instead of iOS as shown in Figure 17-22:

Figure 17-22

To switch to iOS, click on the area marked by the arrow above and select the iOS option from the resulting menu together with a device or simulator as illustrated below:

Figure 17-23

Clicking on the Run toolbar button (marked B in Figure 17-21 above) will compile the code and run the app on the selected target. The small panel in the center of the Xcode toolbar (D) will report the progress of the build process together with any problems or errors that cause the build process to fail. Once the app is built, the simulator will start and the app will run. Clicking on the stop button (A) will terminate the running app.

The simulator includes a number of options not available in the Live Preview for testing different aspects of the app. The Hardware and Debug menus, for example, include options for rotating the simulator through portrait and landscape orientations, testing Face ID authentication and simulating geographical location changes for navigation and map-based apps.

Running the App on a Physical iOS Device

Although the Simulator environment provides a useful way to test an app on a variety of different iOS device models, it is important to also test on a physical iOS device.

If you have entered your Apple ID in the Xcode preferences screen as outlined in the “Joining the Apple Developer Program” chapter and selected a development team for the project, it is possible to run the app on a physical device simply by connecting it to the development Mac system with a USB cable and selecting it as the run target within Xcode.

With a device connected to the development system, and an application ready for testing, refer to the device menu located in the Xcode toolbar. There is a reasonable chance that this will have defaulted to one of the iOS Simulator configurations. Switch to the physical device by selecting this menu and changing it to the device name listed under the iOS Devices section as shown in Figure 17-24:

Figure 17-24

With the target device selected, make sure the device is unlocked and click on the run button at which point Xcode will install and launch the app on the device.

As will be discussed later in this chapter, a physical device may also be configured for network testing, whereby apps are installed and tested on the device via a network connection without the need to have the device connected by a USB cable.

Managing Devices and Simulators

Currently connected iOS devices and the simulators configured for use with Xcode can be viewed and managed using the Xcode Devices window which is accessed via the Window -> Devices and Simulators menu option. Figure 17-25, for example, shows a typical Device screen on a system where an iPhone has been detected:

Figure 17-25

A wide range of simulator configurations are set up within Xcode by default and can be viewed by selecting the Simulators button at the top of the left-hand panel. Other simulator configurations can be added by clicking on the + button located in the bottom left-hand corner of the window. Once selected, a dialog will appear allowing the simulator to be configured in terms of device model, iOS version and name.

Enabling Network Testing

In addition to testing an app on a physical device connected to the development system via a USB cable, Xcode also supports testing via a network connection. This option is enabled on a per device basis within the Devices and Simulators dialog introduced in the previous section. With the device connected via the USB cable, display this dialog, select the device from the list and enable the Connect via network option as highlighted in Figure 17-26:

Figure 17-26

Once the setting has been enabled, the device may continue to be used as the run target for the app even when the USB cable is disconnected. The only requirement being that both the device and development computer be connected to the same Wi-Fi network. Assuming this requirement has been met, clicking on the run button with the device selected in the run menu will install and launch the app over the network connection.

Dealing with Build Errors

If for any reason a build fails, the status window in the Xcode toolbar will report that an error has been detected by displaying “Build” together with the number of errors detected and any warnings. In addition, the left-hand panel of the Xcode window will update with a list of the errors. Selecting an error from this list will take you to the location in the code where corrective action needs to be taken.

Monitoring Application Performance

Another useful feature of Xcode is the ability to monitor the performance of an application while it is running, either on a device or simulator or within the Live Preview canvas. This information is accessed by displaying the Debug Navigator.

When Xcode is launched, the project navigator is displayed in the left-hand panel by default. Along the top of this panel is a bar with a range of other options. The seventh option from the left displays the debug navigator when selected as illustrated in Figure 17-27. When displayed, this panel shows a number of real-time statistics relating to the performance of the currently running application such as memory, CPU usage, disk access, energy efficiency, network activity and iCloud storage access.

Figure 17-27

When one of these categories is selected, the main panel (Figure 17-28) updates to provide additional information about that particular aspect of the application’s performance:

Figure 17-28

Yet more information can be obtained by clicking on the Profile in Instruments button in the top right-hand corner of the panel.

Exploring the User Interface Layout Hierarchy

Xcode also provides an option to break the user interface layout out into a rotatable 3D view that shows how the view hierarchy for a user interface is constructed. This can be particularly useful for identifying situations where one view instance is obscured by another appearing on top of it or a layout is not appearing as intended. This is also useful for learning how SwiftUI works behind the scenes to construct a SwiftUI layout, if only to appreciate how much work SwiftUI is saving us from having to do.

To access the view hierarchy in this mode, the app needs to be running on a device or simulator. Once the app is running, click on the Debug View Hierarchy button indicated in Figure 17-29:

Figure 17-29

Once activated, a 3D “exploded” view of the layout will appear. Clicking and dragging within the view will rotate the hierarchy allowing the layers of views that make up the user interface to be inspected:

Figure 17-30

Moving the slider in the bottom left-hand corner of the panel will adjust the spacing between the different views in the hierarchy. The two markers in the right-hand slider (Figure 17-31) may also be used to narrow the range of views visible in the rendering. This can be useful, for example, to focus on a subset of views located in the middle of the hierarchy tree:

Figure 17-31

While the hierarchy is being debugged, the left-hand panel will display the entire view hierarchy tree for the layout as shown in Figure 17-32 below:

Figure 17-32

Selecting an object in the hierarchy tree will highlight the corresponding item in the 3D rendering and vice versa. The far right-hand panel will also display the attributes of the selected object. Figure 17-33, for example, shows the inspector panel while a Text view is selected within the view hierarchy.

Figure 17-33

Summary

When creating a new project, Xcode provides the option to use either UIKit Storyboards or SwiftUI as the basis of the user interface of the app. When in SwiftUI mode, most of the work involved in developing an app takes place in the code editor and the preview canvas. New views can be added to the user interface layout and configured either by typing into the code editor or dragging and dropping components from the Library either onto the editor or the preview canvas.

The preview canvas will usually update in real-time to reflect code changes as they are typed into the code editor, though will frequently pause updates in response to larger changes. When in the paused state, clicking the Resume button will restart updates. The Attribute inspector allows the properties of a selected view to be changed and new modifiers added. Holding down the Command key while clicking on a view in the editor or canvas displays the context menu containing a range of options such as embedding the view in a container or extracting the selection to a subview.

The preview structure at the end of the SwiftUI View file allows previewing to be performed on multiple device models simultaneously and with different environment settings.