A SwiftUI Charts Tutorial

The objective of this chapter is to demonstrate the main features of the SwiftUI Charts in the form of a tutorial. Topics covered include creating a chart, displaying data from multiple data sources, and use of the style modifier.

The concept behind the tutorial is a chart that displays monthly unit sales containing graphs for both online and retail sales channels.

Creating the ChartDemo Project

Launch Xcode and select the usual options to create a new multiplatform project named ChartDemo.

Adding the Project Data

The first requirement for handling the sales data is to declare a structure to store data for each month. Right-click on the ChartDemo folder in the Project Navigator panel, select the New File… menu option and create a new SwiftUI file named SalesData.swift. Edit the file and add the following struct declaration:

import Foundation

struct SalesInfo: Identifiable {
    var id = UUID()
    var month: String
    var total: Int
}

Remaining within the SalesData.swift file, add two arrays containing the retail and online sales data for January through July as follows:

.
.
var retailSales: [SalesInfo] = [
    .init(month: "Jan", total: 5),
    .init(month: "Feb", total: 7),
    .init(month: "March", total: 6),
    .init(month: "April", total: 5),
    .init(month: "May", total: 6),
    .init(month: "June", total: 3),
    .init(month: "July", total: 6)
]

var onlineSales: [SalesInfo] = [
    .init(month: "Jan", total: 2),
    .init(month: "Feb", total: 4),
    .init(month: "March", total: 5),
    .init(month: "April", total: 2),
    .init(month: "May", total: 4),
    .init(month: "June", total: 1),
    .init(month: "July", total: 4)    
]

Our next requirement is a third array that combines the data from both sales channels. Each element in this third array will also need to include a label string that can be used later when the time comes to split the data into separate channel graphs. Add this array now within the ContentView.swift file. Now is also a good opportunity to import the Charts framework:

import SwiftUI
import Charts

struct ContentView: View {
    var body: some View {

        let sales = [ (channel: "Retail", data: retailSales),
                        (channel: "Online", data: onlineSales) ]
.
.

Adding the Chart View

The chart view is going to need to use nested ForEach loops. The outer loop will iterate through the channel entries in the sales array while the inner loop will iterate through the sales data for each channel. Start by adding the Chart view and the outer loop as follows:

struct ContentView: View {
    var body: some View {

        let sales = [ (channel: "Retail", data: retailSales),
                        (channel: "Online", data: onlineSales) ]

        Chart {
            ForEach(sales, id: \.channel) { channels in
                
            }
        }
        .frame(height: 250)
        .padding()
   }
}

The outer loop passes the set of channels to the inner loop where we can then iterate through the sales data. For each month in the data, the inner ForEach loop will need to add an AreaMark instance configured with the month name and sales total. Modify the Chart view declaration so that it reads as follows:

Chart {
    ForEach(sales, id: \.channel) { channels in
        ForEach(channels.data) { sales in
            AreaMark(
                x: .value("Month", sales.month),
                y: .value("Total", sales.total)
            )
        }
    }
}
.
.

Review the chart in the Preview panel where it should appear as shown in Figure 1-1 below:

Figure 1-1

At this point, the chart is not appearing as intended because we have not taken any steps to separate the online and retail sales data. To divide the data into two graphs we will need to apply the foregroundStyle() modifier to the AreaMark declaration and configure it to filter the data based on the sales channel.

Creating Multiple Graphs

Edit the ContentView.swift file once again, locate the AreaMark instance, and apply the foregroundStyle() modifier:

Chart {
    ForEach(sales, id: \.channel) { channels in
        ForEach(channels.data) { sales in
            AreaMark(
                x: .value("Month", sales.month),
                y: .value("Total", sales.total)
            )
            .foregroundStyle(by: .value("Channel", channels.channel))
        }
    }
}

Preview the chart once again and confirm that it now appears correctly as shown in Figure 1-2:

Figure 1-2

Now that the project is complete, take some time to experiment with the chart by adding symbols and using different mark types and interpolation methods. Figure 1-3, for example, shows the effect of replacing AreaMark with PointMark:

Figure 1-3

Summary

In this chapter, we have created a project that uses SwiftUI Charts to visualize two sets of data in the form of area graphs. Steps covered in the tutorial included the use of the Chart and AreaMark components and the use of the foreground style modifier.

An Overview of SwiftUI Charts

One of the best ways to present data is to do so in the form of a chart or graph. While it has always been possible, given sufficient time and skills, to generate charts in SwiftUI by writing your own data handling and drawing code, it was not until the introduction of the SwiftUI Charts API that it became a simple as writing a few lines of code. In this chapter, we will explore the more commonly used features of SwiftUI Charts before creating a project in the next chapter that will allow you to see Charts in action and experiment with the main features of this API.

Introducing SwiftUI Charts

SwiftUI Charts consists of views and modifiers that allow you to visually present data, typically with just a few lines of code. The API is highly configurable and includes options to present data in the form of area, line, point, rectangle, bar, and stacked bar graphs. The Chart view also includes the rule mark which draws a straight line between specified start and end coordinates. The top-level view in any chart implementation is the Chart view. Each data point within a Chart takes the form of a mark view. The type of mark view used will depend on the chart style. For example, a bar chart will be made up of instances of BarMark, while an area graph will contain AreaMark instances. The Charts API supports the following mark types:

  • AreaMark
  • BarMark
  • LineMark
  • PointMark
  • RectangleMark
  • RuleMark

Each mark must be initialized with x and y values, each of which is represented by an instance of the PlottableValue class. The following declaration, for example, creates an area chart consisting of three marks (note that the Charts library must be imported when working with this API):

.
.
import Charts
.
.
Chart {
    AreaMark(
        x: PlottableValue.value("Month", "Jan"),
        y: PlottableValue.value("Temp", 50)
    )
    AreaMark(
        x: PlottableValue.value("Month", "Feb"),
        y: PlottableValue.value("Temp", 43)
    )
    AreaMark(
        x: PlottableValue.value("Month", "Mar"),
        y: PlottableValue.value("Temp", 61)
    )
}

For tidier code, the PlottableValue.value declarations can be abbreviated to .value, for example:

AreaMark(
    x: .value("Month", "Jan"),
    y: .value("Temp", 50)
)

The above example will generate a chart matching that shown in Figure 1-1 below:

Figure 1-1

Passing Data to the Chart

In the previous example, we manually coded each point on the chart. It is more likely, however, that the data to be plotted exists outside of the chart. In this situation we can pass the data as a parameter to the Chart view as follows:

struct MonthlyTemp: Identifiable {
    var id = UUID()
    var month: String
    var degrees: Int
}

let tempData: [MonthlyTemp] = [
    MonthlyTemp(month: "Jan", degrees: 50),
    MonthlyTemp(month: "Feb", degrees: 43),
    MonthlyTemp(month: "Mar", degrees: 61)
]

Chart(tempData) { data in
    AreaMark(
        x: .value("Month", data.month),
        y: .value("Temp", data.degrees)
    )
}

The above code will create the same chart illustrated in Figure 1-1. A ForEach loop will produce the same result:

Chart {
    ForEach(tempData) { data in
        AreaMark(
            x: .value("Month", data.month),
            y: .value("Temp", data.degrees)
        )
    }
}

Combining Mark Types

So far in this chapter, we have only displayed data using one type of graph. We can display the same data in different ways within the same chart. In the following example, our temperature data appears in both rectangle and line format:

Chart(tempData) { data in
    RectangleMark(
        x: .value("Month", data.month),
        y: .value("Temp", data.degrees)
    )
    LineMark(
        x: .value("Month", data.month),
        y: .value("Temp", data.degrees)
    )
}

This code will generate the graph shown in Figure 1-2:

Figure 1-2

Filtering Data into Multiple Graphs

If the data contains information that allows it to be filtered into categories, the foregroundStyle() modifier can be used to generate multiple graphs within a single chart instance. Suppose, for example, that our temperature data includes values for more than one year. This data might be declared as follows:

struct MonthlyTemp: Identifiable {
    var id = UUID()
    var month: String
    var degrees: Int
    var year: String
}

let tempData: [MonthlyTemp] = [
    MonthlyTemp(month: "Jan", degrees: 50, year: "2021"),
    MonthlyTemp(month: "Feb", degrees: 43, year: "2021"),
    MonthlyTemp(month: "Mar", degrees: 61, year: "2021"),
    
    MonthlyTemp(month: "Jan", degrees: 30, year: "2022"),
    MonthlyTemp(month: "Feb", degrees: 38, year: "2022"),
    MonthlyTemp(month: "Mar", degrees: 29, year: "2022")
]

The only change required to the Chart code is to apply the foregroundStyle() modifier to the mark declaration and pass it a PlottableValue instance configured to separate the data by year:

Chart {
    ForEach(tempData) { data in
        LineMark(
            x: .value("Month", data.month),
            y: .value("Temp", data.degrees)
        )
        .foregroundStyle(by: .value("Year", data.year))
    }
}

The chart will now separate the data into two lines, each rendered in a different color. Note also that a scale appears at the bottom of the chart showing the correspondence between colors and years:

Figure 1-3

Presenting Data with SwiftUI Charts In addition to the line colors, we can also add symbols at each mark point to further differentiate the data categories. We do this by applying the symbol() modifier to the mark declaration passing as a parameter an appropriately configured PlottableValue instance as outlined above for the foregroundStyle() modifier:

Chart {
    ForEach(tempData) { data in
        LineMark(
            x: .value("Month", data.month),
            y: .value("Temp", data.degrees)
        )
        .foregroundStyle(by: .value("Year", data.year))
        .symbol(by: .value("Year", data.year))
    }
}

A close inspection of the two lines in our chart will show that the lines are using different symbols for the mark points:

Figure 1-4

Changing the Chart Background

The background of the Chart view can be changed using the chartPlotStyle() modifier. This modifier is used with a trailing closure to which it passes a reference to the plot area on which the graph is being drawn. This reference may then be used to change properties such as the background color:

Chart {
.
.
}
.chartPlotStyle { plotArea in
    plotArea
        .background(.gray.opacity(0.3))
}
.
.

Changing the Interpolation Method

Interpolation refers to how lines are drawn to connect the data points in a graph. The interpolation method used by a chart can be changed by applying the interpolationMethod() modifier to mark declarations. The list of interpolation options is as follows:

  • cardinal
  • catmullRom
  • linear
  • monotone
  • stepCenter
  • stepEnd
  • stepStart

The following code example configures our example chart to use stepStart interpolation:

Chart {
    ForEach(tempData) { data in
        LineMark(
            x: .value("Month", data.month),
            y: .value("Temp", data.degrees)
        )
        .interpolationMethod(.stepStart)
        .foregroundStyle(by: .value("Year", data.year))
        .symbol(by: .value("Year", data.year))
    }
}

The resulting chart using stepStart interpolation will appear as shown below:

Figure 1-5

Summary

SwiftUI Charts provides an intuitive way to visualize data in the form of charts and graphs with minimal coding. This is achieved using a parent Chart view containing data points in the form of mark instances. Marks are available for several graph types including area, line, bar, plot, and rectangle. The x and y data for each mark is, in turn, contained within a PlottableValue instance. Graphs can be combined and configured using modifiers including changing the interpolation style and adding point symbol markers.

A SwiftUI NavigationStack Tutorial

The previous chapter introduced the List, NavigationStack, and NavigationLink views and explained how these can be used to present a navigable and editable list of items to the user. This chapter will work through the creation of a project intended to provide a practical example of these concepts.

About the ListNavDemo Project

When completed, the project will consist of a List view in which each row contains a cell displaying image and text information. Selecting a row within the list will navigate to a details screen containing more information about the selected item. In addition, the List view will include options to add and remove entries and to change the ordering of rows in the list.

The project extensively uses state properties and observable objects to keep the user interface synchronized with the data model.

Creating the ListNavDemo Project

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

Preparing the Project

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

Before beginning the development of the app project, some preparatory work needs to be performed involving the addition of image and data assets which will be needed later in the chapter.

The assets to be used in the project are included in the source code sample download provided with the book available from the following URL:

https://www.ebookfrenzy.com/web/swiftui-ios15/

Once the code samples have been downloaded and unpacked, open a Finder window, and locate the CarAssets.xcassets folder and drag and drop it onto the project navigator panel as illustrated in Figure 31-1:

Figure 31-1

When the options dialog appears, enable the Copy items if needed option so that the assets are included within the project folder before clicking on the Finish button. With the image assets added, find the carData.json file located in the CarData folder and drag and drop it onto the Project navigator panel to also add it to the project.

This JSON file contains entries for different hybrid and electric cars including a unique id, model, description, a Boolean property indicating whether or not it is a hybrid vehicle, and the filename of the corresponding car image in the asset catalog. The following, for example, is the JSON entry for the Tesla Model 3:

{
    "id": "aa32jj887hhg55",
    "name": "Tesla Model 3",
    "description": "Luxury 4-door all-electric car. Range of 310 miles. 0-60mph in 3.2 seconds ",
    "isHybrid": false,
    "imageName": "tesla_model_3"
}

Adding the Car Structure

Now that the JSON file has been added to the project, a structure needs to be declared to represent each car model. Add a new Swift file to the project by selecting the File -> New -> File… menu option, selecting Swift File in the template dialog and clicking on the Next button. Name the file Car.swift on the subsequent screen before clicking on the Create button.

Once created, the new file will load into the code editor where it needs to be modified so that it reads as follows:

import SwiftUI
 
struct Car : Codable, Identifiable {
    var id: String
    var name: String
    
    var description: String
    var isHybrid: Bool
    
    var imageName: String
}

As we can see, the structure contains a property for each field in the JSON file and is declared as conforming to the Identifiable protocol so that each instance can be uniquely identified within the List view.

31.5 Loading the JSON Data

The project will also need a way to load the carData.json file and translate the car entries into an array of Car objects. For this, we will add another Swift file containing a convenience function that reads the JSON file and initializes an array that can be accessed elsewhere in the project.

Using the steps outlined previously, add another Swift file named CarData.swift to the project and modify it as follows:

import UIKit
import SwiftUI
 
var carData: [Car] = loadJson("carData.json")
 
func loadJson<T: Decodable>(_ filename: String) -> T {
    let data: Data
    
    guard let file = Bundle.main.url(forResource: filename, 
                                  withExtension: nil)
    else {
        fatalError("\(filename) not found.")
    }
    
    do {
        data = try Data(contentsOf: file)
    } catch {
        fatalError("Could not load \(filename): \(error)")
    }
    
    do {
        return try JSONDecoder().decode(T.self, from: data)
    } catch {
        fatalError("Unable to parse \(filename): \(error)")
    }
}

The file contains a variable referencing an array of Car objects which is initialized by a call to the loadJson() function. The loadJson() function is a standard example of how to load a JSON file and can be used in your own projects.

Adding the Data Store

When the user interface has been designed, the List view will rely on an observable object to ensure that the latest data is always displayed to the user. So far, we have a Car structure and an array of Car objects loaded from the JSON file to act as a data source for the project. The last step in getting the data ready for use in the app is to add a data store structure. This structure will need to contain a published property that can be observed by the user interface to keep the List view up to date. Add another Swift file to the project, this time named CarStore. swift, and implement the class as follows:

import SwiftUI
import Combine
 
class CarStore : ObservableObject {
    
    @Published var cars: [Car]
    
    init (cars: [Car] = []) {
        self.cars = cars
    }
}

This file contains a published property in the form of an array of Car objects and an initializer which is passed the array to be published.

With the data side of the project complete, it is now time to begin designing the user interface.

Designing the Content View

Select the ContentView.swift file and modify it as follows to add a state object binding to an instance of CarStore, passing through to its initializer the carData array created in the CarData.swift file:

import SwiftUI
 
struct ContentView: View {
    
    @StateObject var carStore : CarStore = CarStore(cars: carData)
.
.

The content view is going to require a List view to display information about each car. Now that we have access to the array of cars via the carStore property, we can use a ForEach loop to display a row for each car model. The cell for each row will be implemented as an HStack containing an Image and a Text view, the content of which will be extracted from the carData array elements. Remaining in the ContentView.swift file, delete the existing views and implement the list as follows:

.
.
var body: some View {
    
        List {
            ForEach (0..<carStore.cars.count, id: \.self) { i in
                HStack {
                    Image(carStore.cars[i].imageName)
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 100, height: 60)
                    Text(carStore.cars[i].name)
               }
            }
        }
    }
}
.
.

With the change made to the view, use the preview canvas to verify that the list populates with content as shown in Figure 31-2:

Figure 31-2

Before moving to the next step in the tutorial, the cell declaration will be extracted to a subview to make the declaration tidier. Within the editor, hover the mouse pointer over the HStack declaration and hold down the keyboard Command key so that the declaration highlights. With the Command key still depressed, left-click and select the Extract Subview menu option:

Figure 31-3

Once the view has been extracted, change the name from the default ExtractedView to ListCell. Because the ListCell subview is used within a ForEach statement, the current car will need to be passed through when it is used. Modify both the ListCell declaration and the reference as follows to remove the syntax errors:

    var body: some View {
        
            List {
                ForEach (0..<carStore.cars.count, id: \.self) { i in
                    ListCell(car: carStore.cars[i])
            }
        }
    }
}
 
struct ListCell: View {
    
    var car: Car
    
    var body: some View {
        HStack {
            Image(car.imageName)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 100, height: 60)
            Text(car.name)
        }
    }
}

Use the preview canvas to confirm that the extraction of the cell as a subview has worked successfully.

Designing the Detail View

When a user taps a row in the list, a detail screen will appear showing additional information about the selected car. The layout for this screen will be declared in a separate SwiftUI View file which now needs to be added to the project. Use the File -> New -> File… menu option once again, this time selecting the SwiftUI View template option and naming the file CarDetail.

When the user navigates to this view from within the List, it will need to be passed the Car instance for the selected car so that the correct details are displayed. Begin by adding a property to the structure and configuring the preview provider to display the details of the first car in the carData array within the preview canvas as follows:

import SwiftUI
 
struct CarDetail: View {
    
    let selectedCar: Car
    
    var body: some View {
.
.
    }
}
 
struct CarDetail_Previews: PreviewProvider {
    static var previews: some View {
        CarDetails(selectedCar: carData[0])
    }
}

For this layout, a Form container will be used to organize the views. This is a container view that allows views to be grouped and divided into different sections. The Form also places a line divider between each child view.

Within the body of the CarDetail.swift file, implement the layout as follows:

var body: some View {
    Form {
        Section(header: Text("Car Details")) {
            Image(selectedCar.imageName)
                .resizable()
                .cornerRadius(12.0)
                .aspectRatio(contentMode: .fit)
                .padding()
                
                Text(selectedCar.name)
                    .font(.headline)
        
                Text(selectedCar.description)
                    .font(.body)
    
                HStack {
                    Text("Hybrid").font(.headline)
                    Spacer()
                    Image(systemName: selectedCar.isHybrid ?
                            "checkmark.circle" : "xmark.circle" )
                }
          }
    }
}

Note that the Image view is configured to be resizable and scaled to fit the available space while retaining the aspect ratio. Rounded corners are also applied to make the image more visually appealing and either a circle or checkmark image is displayed in the HStack based on the setting of the isHybrid Boolean setting of the selected car.

When previewed, the screen should match that shown in Figure 31-4:

Figure 31-4

Adding Navigation to the List

The next step in this tutorial is to return to the List view in the ContentView.swift file and implement navigation so that selecting a row displays the detail screen populated with the corresponding car details.

With the ContentView.swift file loaded into the code editor, locate the call to the ListCell subview declaration and embed it within a NavigationLink using the current ForEach counter as the link value:

var body: some View {
    List {
        ForEach (0..<carStore.cars.count, id: \.self) { i in
            NavigationLink(value: i) {
                ListCell(car: carStore.cars[i])
            }
        }
    
    }
}

For this navigation link to function, the List view must also be embedded in a NavigationStack as follows:

var body: some View {
    NavigationStack {
        List {
            ForEach (0..<carStore.cars.count, id: \.self) { i in
                NavigationLink(value: i) {
                    ListCell(car: carStore.cars[i])
                }
            }
        }
    }
}

Next, we need to add the navigation destination modifier to the list so that tapping an item navigates to the CarDetail view containing details of the selected car:

NavigationStack {
    List {
        ForEach (0..<carStore.cars.count, id: \.self) { i in
            NavigationLink(value: i) {
                ListCell(car: carStore.cars[i])
            }
        }
    }
    .navigationDestination(for: Int.self) { i in
        CarDetail(selectedCar: carStore.cars[i])
    }
}

Test that the navigation works using the preview canvas in Live mode and selecting different rows, confirming each time that the detail view appears containing information matching the selected car model.

Designing the Add Car View

The final view to be added to the project is the screen to be displayed when the user is adding a new car to the list. Add a new SwiftUI View file to the project named AddNewCar.swift including some state properties and a declaration for storing a reference to the carStore binding (this reference will be passed to the view from the ContentView when the user taps an Add button). Also, modify the preview provider to pass the carData array into the view for testing purposes:

import SwiftUI
 
struct AddNewCar: View {
    
    @StateObject var carStore : CarStore  
    @State private var isHybrid = false
    @State private var name: String = ""
    @State private var description: String = ""
.
.
struct AddNewCar_Previews: PreviewProvider {
    static var previews: some View {
        AddNewCar(carStore: CarStore(cars: carData))
    }
}

Next, add a new subview to the declaration that can be used to display a Text and TextField view pair into which the user will enter details of the new car. This subview will be passed a String value for the text to appear on the Text view and a state property binding into which the user’s input is to be stored. As outlined in the chapter entitled SwiftUI State Properties, Observable, State and Environment Objects, a property must be declared using the @Binding property wrapper if the view is being passed a state property. Remaining in the AddNewCar. swift file, implement this subview as follows:

struct DataInput: View {
    
    var title: String
    @Binding var userInput: String
    
    var body: some View {
        VStack(alignment: HorizontalAlignment.leading) {
            Text(title)
                .font(.headline)
            TextField("Enter \(title)", text: $userInput)
                        .textFieldStyle(RoundedBorderTextFieldStyle())
        }
        .padding()
    }
}

With the subview added, declare the user interface layout for the main view as follows:

var body: some View {
    
    Form {
        Section(header: Text("Car Details")) {
            Image(systemName: "car.fill")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .padding()
            
            DataInput(title: "Model", userInput: $name)
            DataInput(title: "Description", userInput: $description)
 
            Toggle(isOn: $isHybrid) {
                    Text("Hybrid").font(.headline)
            }.padding()        
        }
        
        Button(action: addNewCar) {
            Text("Add Car")
            }
        }
}

Note that two instances of the DataInput subview are included in the layout with an Image view, a Toggle, and a Button. The Button view is configured to call an action method named addNewCar when clicked. Within the body of the ContentView declaration, add this function now so that it reads as follows:

.
.
            Button(action: addNewCar) {
                Text("Add Car")
                }
            }
    }
    
    func addNewCar() {
        let newCar = Car(id: UUID().uuidString,
                      name: name, description: description,
                      isHybrid: isHybrid, imageName: "tesla_model_3" )
        
        carStore.cars.append(newCar)
    }
}

The new car function creates a new Car instance using the Swift UUID() method to generate a unique identifier for the entry and the content entered by the user. For simplicity, rather than add code to select a photo from the photo library the function reuses the tesla_model_3 image for new car entries. Finally, the new Car instance is appended to the carStore car array.

When rendered in the preview canvas, the AddNewCar view should match Figure 31-5 below:

Figure 31-5

With this view completed, the next step is to modify the ContentView layout to include Add and Edit buttons.

31.11 Implementing Add and Edit Buttons

The Add and Edit buttons will be added to a navigation bar applied to the List view in the ContentView layout. The Navigation bar will also be used to display a title at the top of the list. These changes require the use of the navigationBarTitle() and navigationBarItems() modifiers as follows:

var body: some View {
    NavigationStack {
        List {
            ForEach (0..<carStore.cars.count, id: \.self) { i in
                NavigationLink(value: i) {
                    ListCell(car: carStore.cars[i])
                }
            }
        }
        .navigationDestination(for: Int.self) { i in
            CarDetail(selectedCar: carStore.cars[i])
        }
        .navigationBarTitle(Text("EV Cars"))
                .navigationBarItems(leading:
                NavigationLink(value: "Add Car") {
                    Text("Add")
                        .foregroundColor(.blue)
                }, trailing: EditButton())
    }
}

The Add button is configured to appear at the leading edge of the navigation bar and is implemented as a NavigationLink using a string value that reads “Add Car”. We now need to add a second navigation destination modifier for this string-based link that displays the AddNewCar view:

NavigationStack {
    List {
        ForEach (0..<carStore.cars.count, id: \.self) { i in
            NavigationLink(value: i) {
                ListCell(car: carStore.cars[i])
            }
        }
    }
    .navigationDestination(for: Int.self) { i in
        CarDetail(selectedCar: carStore.cars[i])
    }
    .navigationDestination(for: String.self) { _ in
        AddNewCar(carStore: self.carStore)
    }
    .navigationBarTitle(Text("EV Cars"))

The Edit button, on the other hand, is positioned on the trailing edge of the navigation bar and is configured to display the built-in EditButton view. A preview of the modified layout at this point should match the following figure:

Figure 31-6

Using Live Preview mode, test that the Add button displays the new car screen and that entering new car details and clicking the Add Car button causes the new entry to appear in the list after tapping the back button to return to the content view screen. Ideally, the Add Car button should automatically return us to the content view without the need to use the back button. To implement this, we will need to use a navigation path.

Adding a Navigation Path

Begin by editing the ContentView.swift file, adding a NavigationPath declaration, and passing it through to the NavigationStack:

struct ContentView: View {
    
    @StateObject var carStore : CarStore = CarStore(cars: carData)
    @State private var stackPath = NavigationPath()
    
    var body: some View {
        NavigationStack(path: $stackPath) {
.
.

Having created a navigation path, we need to pass it to the AddNewCar view so that it can be used to return to the content view within the addNewCar() function. Edit the string-based .navigationDestination() modifier to pass the path binding to the view:

.navigationDestination(for: String.self) { _ in
    AddNewCar(carStore: carStore: self.carStore, path: $stackPath)
}

Edit the AddNewCar.swift file to add the path binding parameter as follows:

struct AddNewCar: View {
    
    @StateObject var carStore : CarStore
    @Binding var path: NavigationPath
.
.

We also need to comment out the preview provider, since the view is now expecting to be passed a navigation view to which we do not have access within the live preview:

/*
struct AddNewCar_Previews: PreviewProvider {
    static var previews: some View {
        AddNewCar(carStore: CarStore(cars: carData))
    }
}
*/

The last task in this phase of the tutorial is to call removeLast() on the navigation path to pop the current view off the navigation stack and return to the content view:

func addNewCar() {
    let newCar = Car(id: UUID().uuidString,
                  name: name, description: description,
                  isHybrid: isHybrid, imageName: "tesla_model_3" )
    
    carStore.cars.append(newCar)
    path.removeLast()
}

Build and run the app on a device or simulator and test that the Add Car button returns to the content view when clicked.

Adding the Edit Button Methods

The final task in this tutorial is to add some action methods to be used by the EditButton view added to the navigation bar in the previous section. Because these actions are to be available for every row in the list, the actions must be applied to the list cells as follows:

var body: some View {
    NavigationStack(path: $stackPath) {
        List {
            ForEach (0..<carStore.cars.count, id: \.self) { i in
                NavigationLink(value: i) {
                    ListCell(car: carStore.cars[i])
                }
            }
            .onDelete(perform: deleteItems)
            .onMove(perform: moveItems)
        }
        .navigationDestination(for: Int.self) { i in
.
.

Next, add the deleteItems() and moveItems() functions within the scope of the body declaration:

.
.
            .navigationBarTitle(Text("EV Cars"))
                    .navigationBarItems(leading:
                    NavigationLink(value: "Add Car") {
                        Text("Add")
                            .foregroundColor(.blue)
                    }, trailing: EditButton())
        }
    }
    
    func deleteItems(at offsets: IndexSet) {
        carStore.cars.remove(atOffsets: offsets)
    }
    
    func moveItems(from source: IndexSet, to destination: Int) {
        carStore.cars.move(fromOffsets: source, toOffset: destination)
    }
}

In the case of the deleteItems() function, the offsets of the selected rows are provided and used to remove the corresponding elements from the car store array. The moveItems() function, on the other hand, is called when the user moves rows to a different location within the list. This function is passed source and destination values which are used to match the row position in the array.

Using Live Preview, click the Edit button and verify that it is possible to delete rows by tapping the red delete icon next to a row and to move rows by clicking and dragging on the three horizontal lines at the far-right edge of a row. In each case, the list contents should update to reflect the changes:

Figure 31-7

Summary

The main objective of this chapter has been to provide a practical example of using lists, navigation views, and navigation links within a SwiftUI project. This included the implementation of dynamic lists and list editing features. The chapter also served to reinforce topics covered in previous chapters including the use of observable objects, state properties, and property bindings. The chapter also introduced some additional SwiftUI features including the Form container view, navigation bar items, and the TextField view.

SwiftUI NavigationStack and NavigationLink Overview

The SwiftUI List view provides a way to present information to the user in the form of a vertical list of rows. Often the items within a list will navigate to another area of the app when tapped by the user. Behavior of this type is implemented in SwiftUI using the NavigationStack and NavigationLink components.

The List view can present both static and dynamic data and may also be extended to allow for the addition, removal, and reordering of row entries.

This chapter will provide an overview of the List View used in conjunction with NavigationStack and NavigationLink in preparation for the tutorial in the next chapter entitled A SwiftUI NavigationStack Tutorial.

SwiftUI Lists

The SwiftUI List control provides similar functionality to the UIKit TableView class in that it presents information in a vertical list of rows with each row containing one or more views contained within a cell. Consider, for example, the following List implementation:

struct ContentView: View {
    var body: some View {
        
        List {
            Text("Wash the car")
            Text("Vacuum house")
            Text("Pick up kids from school bus @ 3pm")
            Text("Auction the kids on eBay")
            Text("Order Pizza for dinner")
        }
    }
}

When displayed in the preview, the above list will appear as shown in Figure 30-1:

Figure 30-1

A list cell is not restricted to containing a single component. In fact, any combination of components can be displayed in a list cell. Each row of the list in the following example consists of an image and text component within an HStack:

List {
    HStack {
        Image(systemName: "trash.circle.fill")
        Text("Take out the trash")
    }
    HStack {
        Image(systemName: "person.2.fill")
        Text("Pick up the kids") }
    HStack {
        Image(systemName: "car.fill")
        Text("Wash the car")
    }
}

The preview canvas for the above view structure will appear as shown in Figure 30-2 below:

Figure 30-2

Modifying List Separators and Rows

The lines used by the List view to separate rows can be hidden by applying the listRowSeparator() modifier to the cell content views. The listRowSeparatorTint() modifier, on the other hand, can be used to change the color of the lines. It is even possible to assign a view to appear as the background of a row using the listRowBackground() modifier. The following code, for example, hides the first separator, changes the tint of the next two separators, and displays a background image on the final row:

List {
    Text("Wash the car")
        .listRowSeparator(.hidden)
    Text("Pick up kids from school bus @ 3pm")
        .listRowSeparatorTint(.green)
    Text("Auction the kids on eBay")
        .listRowSeparatorTint(.red)
    Text("Order Pizza for dinner")
        .listRowBackground(Image("MyBackgroundImage"))
}

The above examples demonstrate the use of a List to display static information. To display a dynamic list of items a few additional steps are required.

SwiftUI Dynamic Lists

A list is considered to be dynamic when it contains a set of items that can change over time. In other words, items can be added, edited, and deleted and the list updates dynamically to reflect those changes.

To support a list of this type, each data element to be displayed must be contained within a class or structure that conforms to the Identifiable protocol. The Identifiable protocol requires that the instance contain a property named id which can be used to uniquely identify each item in the list. The id property can be any Swift or custom type that conforms to the Hashable protocol which includes the String, Int, and UUID types in addition to several hundred other standard Swift types. If you opt to use UUID as the type for the property, the UUID() method can be used to automatically generate a unique ID for each list item.

The following code implements a simple structure for the To Do list example that conforms to the Identifiable protocol. In this case, the id is generated automatically via a call to UUID():

struct ToDoItem : Identifiable {
    var id = UUID()
    var task: String
    var imageName: String
}

For example, an array of ToDoItem objects can be used to simulate the supply of data to the list which can now be implemented as follows:

struct ContentView: View {
 
    @State var listData: [ToDoItem] = [
       ToDoItem(task: "Take out trash", imageName: "trash.circle.fill"),
       ToDoItem(task: "Pick up the kids", imageName: "person.2.fill"),
       ToDoItem(task: "Wash the car", imageName: "car.fill")
       ]
 
    var body: some View {
        
        List(listData) { item in
            HStack {
                Image(systemName: item.imageName)
                Text(item.task)
            }
        }
    }
}
.
.

Now the list no longer needs a view for each cell. Instead, the list iterates through the data array and reuses the same HStack declaration, simply plugging in the appropriate data for each array element.

In situations where dynamic and static content needs to be displayed together within a list, the ForEach statement can be used within the body of the list to iterate through the dynamic data while also declaring static entries. The following example includes a static toggle button together with a ForEach loop for the dynamic content:

struct ContentView: View {
    
    @State private var toggleStatus = true
.
.    
    var body: some View {
        
        List {
            Toggle(isOn: $toggleStatus) {
                Text("Allow Notifications")
            }
            
            ForEach (listData) { item in
                HStack {
                    Image(systemName: item.imageName)
                    Text(item.task)
                }
            }
        }
    }
}

Note the appearance of the toggle button and the dynamic list items in Figure 30-3:

Figure 30-3

A SwiftUI List implementation may also be divided into sections using the Section view, including headers and footers if required. Figure 30-4 shows the list divided into two sections, each with a header:

Figure 30-4

The changes to the view declaration to implement these sections are as follows:

List {
    Section(header: Text("Settings")) {
        Toggle(isOn: $toggleStatus) {
            Text("Allow Notifications")
        }
    }
    
    Section(header: Text("To Do Tasks")) {
        ForEach (listData) { item in
            HStack {
                Image(systemName: item.imageName)
                Text(item.task)
            }
        }
    }
}

Often the items within a list will navigate to another area of the app when tapped by the user. Behavior of this type is implemented in SwiftUI using the NavigationStack and NavigationLink views.

Creating a Refreshable List

The data displayed on a screen is often derived from a dynamic source which is subject to change over time. The standard paradigm within iOS apps is for the user to perform a downward swipe to refresh the displayed data. During the refresh process, the app will typically display a spinning progress indicator after which the latest data is displayed. To make it easy to add this type of refresh behavior to your apps, SwiftUI provides the refreshable() modifier. When applied to a view, a downward swipe gesture on that view will display the progress indicator and execute the code in the modifier closure. For example, we can add refresh support to our list as follows:

List {
    Section(header: Text("Settings")) {
        Toggle(isOn: $toggleStatus) {
            Text("Allow Notifications")
        }
    }
    
    Section(header: Text("To Do Tasks")) {
        ForEach (listData) { item in
            HStack {
                Image(systemName: item.imageName)
                Text(item.task)
            }
        }
    }
}
.refreshable {
    listData = [
        ToDoItem(task: "Order dinner", imageName: "dollarsign.circle.fill"),
        ToDoItem(task: "Call financial advisor", imageName: "phone.fill"),
        ToDoItem(task: "Sell the kids", imageName: "person.2.fill")
        ]
}

Figure 30-5 demonstrates the effect of performing a downward swipe gesture within the List view after adding the above modifier. Note both the progress indicator at the top of the list and the appearance of the updated to-do list items:

Figure 30-5

When using the refreshable() modifier, be sure to perform any time-consuming activities as an asynchronous task using structured concurrency (covered previously in the chapter entitled “An Overview of Swift Structured Concurrency”). This will ensure that the app remains responsive during the refresh.

SwiftUI NavigationStack and NavigationLink

To make items in a list navigable, the first step is to embed the entire list within a NavigationStack. Once the list is embedded, the individual rows must be wrapped in a NavigationLink control which is, in turn, passed a value that uniquely identifies each navigation link within the context of the NavigationStack.

The following changes to our example code embed the List view in a NavigationStack and wrap the row content in a NavigationLink:

NavigationStack {
    List {
        Section(header: Text("Settings")) {
            Toggle(isOn: $toggleStatus) {
                Text("Allow Notifications")
            }
        }
                
        Section(header: Text("To Do Tasks")) {
            ForEach (listData) { item in
                NavigationLink(value: item.task) {
                    HStack {
                        Image(systemName: item.imageName)
                        Text(item.task)
                    }
                }
            }
        }
    }
}

Note that we have used the item task string as the NavigationLink value to uniquely identify each row. The next step is to specify the destination view to which the user is to be taken when the row is tapped. We achieve this by applying the navigationDestination(for:) modifier to the list. When adding this modifier, we need to pass it the value type for which it is to provide navigation. In our example we are using the task string, so we need to specify String.self as the value type. Within the trailing closure of the navigationDestination(for:) call we need to call the view that is to be displayed when the row is selected. This closure is passed the value from the NavigationLink, allowing us to display the appropriate view:

NavigationStack {   
    List {
.
.
        Section(header: Text("To Do Tasks")) {
            ForEach (listData) { item in
                NavigationLink(value: item.task) {
                    HStack {
                        Image(systemName: item.imageName)
                        Text(item.task)
                    }
                }
            }
        }
    }
    .navigationDestination(for: String.self) { task in
        Text("Selected task = \(task)")
    }
}

In this example, the navigation link will simply display a new screen containing the destination Text view displaying the item.task string value. The finished list will appear as shown in Figure 30-6 with the title and chevrons on the far right of each row now visible indicating that navigation is available. Tapping the links will navigate to and display the destination Text view.

Figure 30-6

Navigation by Value Type

The navigationDestination() modifier is particularly useful for adding navigation support to lists containing values of different types, with each type requiring navigation to a specific view. Suppose, for example, that in addition to the string-based task navigation link, we also have a NavigationLink which is passed an integer value indicating the number of tasks in the list. This could be implemented in our example as follows:

NavigationStack {
    
    List {
        
        Section(header: Text("Settings")) {
            Toggle(isOn: $toggleStatus) {
                Text("Allow Notifications")
            }

            NavigationLink(value: listData.count) {
                Text("View Task Count")
            }
        }
.
.

When this link is selected, we need the app to navigate to a Text view that displays the current task count. All this requires is a second navigationDestination() modifier, this time configured to handle Int instead of String values:

.
.
}
    .navigationDestination(for: String.self) { task in
        Text("Selected task = \(task)")
    }
    .navigationDestination(for: Int.self) { count in
        Text("Number of tasks = \(count)")
    }
.
.

This technique allows us to configure multiple navigation destinations within a single navigation stack based solely on the value type passed to each navigation link.

Working with Navigation Paths

As the name suggests, NavigationStack provides a stack on which navigation targets are stored as the user navigates through the screens of an app. When a user navigates from one view to another, a reference to the originating view is pushed onto the stack. If the user then navigates to another view, the current view will also be placed onto the stack. At any point, the user can tap the back arrow displayed in the navigation bar to move back to the previous view. As the user navigates back through the views, each one is popped off the stack until the view from which navigation began is reached.

The views through which a user navigates are called the navigation path. SwiftUI allows us to provide our own path by passing an instance of NavigationPath to the NavigationStack instance as follows:

struct ContentView: View {

   @State private var stackPath = NavigationPath()

   var body: some View {
        
        NavigationStack(path: $stackPath) {
.
.

With NavigationStack using our path, we can perform tasks such as manually popping targets off the stack to jump back multiple navigation levels instead of making the user navigate through the targets individually. We could, for example, configure a button on a view deep within the stack to take the user directly back to the home screen. We can do this by identifying how many navigation targets are in the stack and then removing them via a call to the removeLast() method of the path instance, for example:

var stackCount = stackPath.count
stackpath.removeLast(stackCount)

We can also programmatically navigate to specific destination views by calling the navigation path’s append() method and passing through the navigation value associated with the destination:

stackPath.append(value)

Navigation Bar Customization

The NavigationStack title bar may also be customized using modifiers on the List component to set the title and to add buttons to perform additional tasks. In the following code fragment the title is set to “To Do List” and a button labeled “Add” is added as a bar item and configured to call a hypothetical method named addTask():

NavigationStack {
    List {
.
.
    }
    .navigationBarTitle(Text("To Do List"))
    .navigationBarItems(trailing: Button(action: addTask) {
        Text("Add")
     })
.
.
}

Making the List Editable

It is common for an app to allow the user to delete items from a list and, in some cases, even move an item from one position to another. Deletion can be enabled by adding an onDelete() modifier to each list cell, specifying a method to be called which will delete the item from the data source. When this method is called it will be passed an IndexSet object containing the offsets of the rows being deleted and it is the responsibility of this method to remove the selected data from the data source. Once implemented, the user will be able to swipe left on rows in the list to reveal the Delete button as shown in Figure 30-7:

Figure 30-7

The changes to the example List to implement this behavior might read as follows:

.
.
List {
    Section(header: Text("Settings")) {
        Toggle(isOn: $toggleStatus) {
            Text("Allow Notifications")
        }
    }
    
    Section(header: Text("To Do Tasks")) {
        ForEach (listData) { item in
            NavigationLink(value: item.task) {
                HStack {
                    Image(systemName: item.imageName)
                    Text(item.task)
                }
            }
        }
        .onDelete(perform: deleteItem)
    }
}
.
.
func deleteItem(at offsets: IndexSet) {
    // Delete items from the data source here
}

To allow the user to move items up and down in the list the onMove() modifier must be applied to the cell, once again specifying a method to be called to modify the ordering of the source data. In this case, the method will be passed an IndexSet object containing the positions of the rows being moved and an integer indicating the destination position.

In addition to adding the onMove() modifier, an EditButton instance needs to be added to the List. When tapped, this button automatically switches the list into editable mode and allows items to be moved and deleted by the user. This edit button is added as a navigation bar item which can be attached to a list by applying the navigationBarItems() modifier. The List declaration can be modified as follows to add this functionality:

List {
    Section(header: Text("Settings")) {
        Toggle(isOn: $toggleStatus) {
            Text("Allow Notifications")
        }
    }
    
    Section(header: Text("To Do Tasks")) {
        ForEach (listData) { item in
            NavigationLink(value: item.task) {
                HStack {
                    Image(systemName: item.imageName)
                    Text(item.task)
                }
            }
        }
        .onDelete(perform: deleteItem)
        .onMove(perform: moveItem)
    }
    
}
.navigationBarTitle(Text("To Do List"))
.navigationBarItems(trailing: EditButton())
.
.
func moveItem(from source: IndexSet, to destination: Int) {
    // Reorder items in source data here
}

Viewed within the preview canvas, the list will appear as shown in Figure 30-8 when the Edit button is tapped. Clicking and dragging the three lines on the right side of each row allows the row to be moved to a different list position (in the figure below the “Pick up the kids” entry is in the process of being moved):

Figure 30-8

Hierarchical Lists

SwiftUI also includes support for organizing hierarchical data for display in list format as shown in Figure 30-9 below:

Figure 30-9

This behavior is achieved using features of the List view together with the OutlineGroup and DisclosureGroup views which automatically analyze the parent-child relationships within a data structure to create a browsable list containing controls to expand and collapse branches of data. This topic is covered in detail beginning with the chapter titled An Overview of SwiftUI List, OutlineGroup and DisclosureGroup.

Multicolumn Navigation

NavigationStack provides navigation between views where each destination occupies the entire device screen. SwiftUI also supports multicolumn navigation where the destinations appear together on the screen with each appearing in a separate column. Multicolumn navigation is provided by the NavigationSplitView component and will be covered beginning with the chapter titled Multicolumn Navigation in SwiftUI with NavigationSplitView.

Summary

The SwiftUI List view provides a way to order items in a single column of rows, each containing a cell. Each cell, in turn, can contain multiple views when those views are encapsulated in a container view such as a stack layout. The List view provides support for displaying both static and dynamic items or a combination of both. Lists may also be used to group, organize and display hierarchical data.

List views are used to allow the user to navigate to other screens. This navigation is implemented by wrapping the List declaration in a NavigationStack and each row in a NavigationLink, using the navigationDestination() modifier to define the navigation target view.

Lists can be divided into titled sections and assigned a navigation bar containing a title and buttons. Lists may also be configured to allow rows to be added, deleted, and moved.

A SwiftUI NavigationSplitView Tutorial

The previous chapter introduced us to the SwiftUI NavigationSplitView component and described how multicolumn navigation is implemented and configured. This chapter will take what we have learned about NavigationSplitView and use it to create an example iOS app project.

About the Project

This tutorial will create the three-column split navigation app illustrated in the previous chapter. The sidebar column will list categories which, when selected, will update the content column to list icons belonging to the chosen category. The detail column will, in turn, display the currently selected icon from the content list.

Creating the NavSplitDemo Project

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

Adding the Project Data

Our first requirement is a class declaration we can use to store category names and corresponding icons. Right-click on the NavSplitDemo folder in the Project navigator, select the New File… menu option, and create a new Swift file named IconCategory.swift. With the file added to the project, modify it to declare a structure for storing each icon category:

import Foundation

struct IconCategory: Identifiable, Hashable {
    let id = UUID()
    var categoryName: String
    var images: [String]
}

Next, edit the ContentView.swift file and add a state array variable populated with categories and icon names:

import SwiftUI

struct ContentView: View {

    @State private var categories = [
        IconCategory(categoryName: "Folders", images: ["questionmark.folder.ar",
                                                   "questionmark.folder",
                                                   "questionmark.folder.fill.ar",
                                                   "folder.fill.badge.gear",
                                                   "questionmark.folder.fill"]),
        IconCategory(categoryName: "Circles", images: ["book.circle",
                                                    "books.vertical.circle",
                                                    "books.vertical.circle.fill",
                                                    "book.circle.fill",
                                                    "book.closed.circle"]),
        IconCategory(categoryName: "Clouds", images: ["cloud.rain",
                                                   "cloud",
                                                   "cloud.drizzle.fill",
                                                   "cloud.fill",
                                                   "cloud.drizzle"])
    ]
.
.

Creating the Navigation View

The next step is to replace the default view within the ContentView with a NavigationSplitView as outlined below. As the project requires three columns, we need to include the sidebar, content, and detail declarations:

.
.
var body: some View {
    NavigationSplitView {
        
    } content: {
        
    } detail: {
    
    }
}
.
.

Building the Sidebar Column

Now that we have added the NavigationSplitView we are ready to add the list of categories in the sidebar column. While doing this, we also need to add a state variable to store the currently selected item in the list. Remaining in the ContentView.swift file, make these changes as follows:

.
.
@State private var selectedCategory: IconCategory?
var body: some View {
    NavigationSplitView(columnVisibility: $columnVisibility) {
        List(categories, selection: $selectedCategory) { category in
            Text(category.categoryName).tag(category)
        }
    } content: {
.
.

The code we have added displays a List view where each item is a Text view displaying a category name from the categories array. The List is passed a reference to our selectedCategory state variable for storing the most recent item selection.

Check the Preview panel and verify that the sidebar appears as shown in Figure 1-1 below:

Figure 1-1

Adding the Content Column List

With the sidebar completed, we are ready to add a list within the content column. Since we also need to keep track of the currently selected icon name we will need another state variable. To avoid showing a blank column, we also need to add some code to display a message if the user has not yet made a category selection. We can do this by using an if-let statement to evaluate the selectedCategory state variable:

.
.
@State private var selectedCategory: IconCategory?
@State private var selectedImage: String?

var body: some View {
    NavigationSplitView {
        List(categories, selection: $selectedCategory) { category in
            Text(category.categoryName).tag(category)
        }
    } content: {
        if let selectedCategory {
            List(selectedCategory.images, id: \.self, 
                           selection: $selectedImage) { image in
                HStack {
                    Image(systemName: image)
                    Text(image)
                }.tag(image)
            }
        } else {
            Text("Select a category")
        }
    } detail: {
    
    }
}
.
.

For each item in the list, we are using a horizontal stack containing the icon and name text. Select an iPad or iPhone Pro Max simulator or physical device as the run target and build and run the app. Once the app is running, rotate the device or simulator into landscape orientation. If the app is functioning as expected, selecting items from the sidebar should cause the content column to list the corresponding icon options as shown in Figure 1-2:

Figure 1-2

Adding the Detail Column

The detail column will display the selected icon in response to selections made within the content list. Locate the detail section within the NavigationSplitView declaration and modify it as follows, once again adding code to let the user know an icon needs to be selected:

NavigationSplitView {
    List(categories, selection: $selectedCategory) { category in
        Text(category.categoryName).tag(category)
    }
} content: {
.
.
} detail: {
    if let selectedImage {
        Image(systemName: selectedImage)
            .resizable()
            .aspectRatio(contentMode: .fit)
            .padding()
    } else {
        Text("Select an image")
    }
}

When the app is launched it will appear with only the detail column visible as shown in Figure 1-3:

Figure 1-3

Clicking on the button marked by the arrow in the above figure will display the content column. Unfortunately, since we haven’t yet made a category selection, this column only shows the “Select a category” message. Clicking the Back button will finally give us access to the sidebar column where we can begin to make selections. Once a category and icon have been selected we can see that the detail column is obscured by the sidebar and content panels. To view the entire icon image we have to click on the detail column to hide the other two columns. While this may be the desired behavior in some situations, this is the opposite of the experience we are looking for in our app so some additional configuration is required.

Configuring the Split Navigation Experience

The average user would probably find our split navigation implementation confusing. To make the app more intuitive, we need all three columns to be visible when the app first launches. We can achieve this by passing the all value to the columnVisibility parameter of the NavigationSplitView instance as follows:

.
.
@State private var selectedCategory: IconCategory?
@State private var selectedImage: String?
@State private var columnVisibility = NavigationSplitViewVisibility.all

var body: some View {
    NavigationSplitView(columnVisibility: $columnVisibility) {
        List(categories, selection: $selectedCategory) { category in
            Text(category.categoryName).tag(category)
        }
.
.

When we test the app, we will see all three columns but still have the problem that the detail view is obscured by the sidebar and content columns. The final change is to use the navigationSplitViewStyle() modifier to apply the balanced style:

.
.
           if let selectedImage {
                Image(systemName: selectedImage)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .padding()
            } else {
                Text("Select an image")
            }
        }
        .navigationSplitViewStyle(.balanced)
    }
}
.
.

With this final change applied, the running app should now match Figure 1-4:

Figure 1-4

Summary

In this chapter, we created a SwiftUI-based app project that implements three-column navigation using the NavigationSplitView component. We also changed the default navigation behavior to match the requirements of our app.

Multicolumn Navigation in SwiftUI with NavigationSplitView

The NavigationStack and NavigationLink views outlined in the previous chapters are ideal for adding navigation when each destination view needs to fill the entire device screen. While this is generally the preferred navigation paradigm when working on most iOS devices, it doesn’t take advantage of larger display configurations available on the iPad or the iPhone Pro Max in landscape orientation. To take advantage of wider displays, SwiftUI includes the NavigationSplitView component which is designed to provide multicolumn-based navigation.

In this chapter, we will explain how to use NavigationSplitView in preparation for the next chapter titled A SwiftUI NavigationSplitView Tutorial.

Introducing NavigationSplitView

The purpose of NavigationSplitView is to provide multicolumn-based navigation on wide displays. It supports a maximum of three columns consisting of the sidebar (marked A in Figure 1-1), content (B), and detail (C) columns. A selection in one column controls the content displayed in the next column. The screen in Figure 1-1 shows the example app we will create in the next chapter. In this case, the app is running on an iPhone Pro Max in landscape orientation:

Figure 1-1

When a NavigationSplitView instance runs on narrower displays it behaves similarly to the NavigationStack where each destination view fully occupies the screen.

Using NavigationSplitView

NavigationSplitView uses a simple syntax that differs depending on whether you need two or three-column navigation. The following syntax is for two-column navigation, which consists of the sidebar and detail columns:

NavigationSplitView {
    // Sidebar List here
}  detail: {
    // Detail view here    
}

Three-column navigation consists of sidebar, content, and detail columns declared using the following syntax:

NavigationSplitView {
    // Sidebar List here
} content: {
    // Content List here
} detail: {
    // Detail view here
}

Handling List Selection

Both the sidebar and content columns will typically contain a List view from which the user will choose the content to be displayed in the next column. Selections made in a column are tracked by declaring a state variable and passing it to the List view via the selection parameter, for example:

@State private var colors = ["Red", "Green", "Blue"]
@State private var selectedColor: String?
    
var body: some View {
    NavigationSplitView {
        List(colors, id: \.self, selection: $selectedColor) { color in
            Text(color).tag(color)
        }
    } detail: {
        Text( selectedColor ?? "No color selected")
    }
}

In the code above, for example, the selection made within the List of color names controls the content displayed by the detail column via the selectedColor state variable. Note that the tag() modifier has been applied to the

Text list item. This is used by SwiftUI to differentiate between selectable items in views such as List, Picker, and TabView.

NavigationSplitView Configuration

Several options are available to customize the appearance of a NavigationSplitView. For example, the width of an individual column can be controlled using the navigationSplitViewColumnWidth() modifier. In the following code the sidebar column has been assigned a fixed width of 100 points:

NavigationSplitView {
    List(colors, id: \.self, selection: $selectedColor) { color in
        Text(color).tag(color)
    }
    .navigationSplitViewColumnWidth(100)
} detail: {
    Text( selectedColor ?? "No color selected")
}

Style options can also be configured by applying the navigationSplitViewStyle() modifier to the NavigationSplitView parent declaration as follows:

NavigationSplitView {
    List(colors, id: \.self, selection: $selectedColor) { color in
        Text(color).tag(color)
    }
} detail: {
    Text( selectedColor ?? "No color selected")
}

NavigationSplitView supports the following style options:

  • automatic – This style allows the navigation view to decide how to present columns based on factors such as current content, screen size, and column selections.
  • balanced – The balanced style reduces the width of the detail column when necessary to provide space for the sidebar and content columns.
  • prominentDetail – This style prevents the size of the detail column from changing when the sidebar and content columns are added and removed from view. This style usually results in the sidebar and content columns overlapping the detail column.

Controlling Column Visibility

Column visibility can be controlled programmatically by passing an appropriately configured state value to the NavigationSplitView via its columnVisibility initialization parameter. Changes to the state value will dynamically update the column visibility. Visibility options are provided by the NavigationSplitViewVisibility structure which includes the following options:

  • automatic – Allows the navigation view to decide which columns should be visible based on the available screen space.
  • all – Displays the sidebar, content, and detail columns.
  • doubleColumn – In a two-column configuration, this setting displays the sidebar and detail columns. In a three-column configuration, only the content and detail columns will be visible.
  • detailOnly – Only the detail column is visible.

The following code provides an example of setting column visibility based on a state variable set to detailOnly:

.
.
@State private var colors = ["Red", "Green", "Blue"]
@State private var selectedColor: String?
@State private var columnVisibility = NavigationSplitViewVisibility.detailOnly

var body: some View {
    NavigationSplitView(columnVisibility: $columnVisibility) {
        List(colors, id: \.self, selection: $selectedColor) { color in
            Text(color).tag(color)
        }
    } detail: {
        Text( selectedColor ?? "No color selected")
    }
    .navigationSplitViewStyle(.automatic)
}

Summary

The NavigationSplitView component allows you to build multicolumn-based navigation into your SwiftUI apps. When enough screen width is available, the NavigationSplitView will display up to three columns consisting of sidebar, content, and detail columns. The sidebar and content panels contain List view items that, when selected, control the content in the next column. Selection handling is implemented by passing a state variable to the selection parameter of the column’s List view. The column widths and style of a split navigation user interface can be configured using the navigationSplitViewColumnWidth() and navigationSplitViewStyle() modifiers. Several combinations of column visibility may be configured programmatically using the NavigationSplitView columnVisibility initialization parameter.

A SwiftUI Grid and GridRow Tutorial

The previous chapter introduced LazyHGrid, LazyVGrid, and GridItem views and explored how they can be used to create scrollable multicolumn layouts. While these views can handle large numbers of rows, they lack flexibility, particularly in grid cell arrangement and positioning.

In this chapter, we will work with two grid layout views (Grid and GridRow) that were introduced in iOS 16. While lacking support for large grid layouts, these two views provide several features that are not available when using the lazy grid views including column spanning cells, empty cells, and a range of alignment and spacing options.

Grid and GridRow Views

A grid layout is defined using the Grid view with each row represented by a GridRow child, and direct child views of a GridRow instance represent the column cells in that row.

The syntax for declaring a grid using Grid and GridRow is as follows:

Grid {
    
    GridRow {
        // Cell views here
    }
    
    GridRow {
        // Cell views here
    }
.
.
}

Creating the GridRowDemo Project

Launch Xcode and select the option to create a new Multiplatform App project named GridRowDemo. Once the project is ready, edit the ContentView.swift file to add a custom view to be used as the content for the grid cells in later examples:

struct CellContent: View {

    var index: Int
    var color: Color

    var body: some View {
        Text("\(index)")
            .frame(minWidth: 50, maxWidth: .infinity, minHeight: 100)
            .background(color)
            .cornerRadius(8)
            .font(.system(.largeTitle))
    }
}

A Simple Grid Layout

As a first step, we will create a simple grid 5 x 3 grid by modifying the body of the ContentView structure in the ContentView.swift file as follows:

struct ContentView: View {
    var body: some View {

        Grid {
            GridRow {
                ForEach(1...5, id: \.self) { index in
                    CellContent(index: index, color: .red)
                }
            }
            
            GridRow {
                ForEach(6...10, id: \.self) { index in
                    CellContent(index: index, color: .blue)
                }
            }
            
            GridRow {
                ForEach(11...15, id: \.self) { index in
                    CellContent(index: index, color: .green)
                }
            }
        }
        .padding()
    }
}

The above example consists of a Grid view parent containing three GridRow children. Each GridRow contains a ForEach loop that generates three CellContent views. After making these changes, the layout should appear within the Preview panel, in turn, as shown in Figure 1-1:

Figure 1-1

Non-GridRow Children

So far in this chapter, we have implied that the direct children of a Grid view must be GridRows. While this is the most common use of the Grid view, it is also possible to include children outside the scope of a GridRow. Grid children not contained within a GridRow will expand to occupy an entire row within the grid layout.

The following changes, for example, add a fourth row to the grid containing a single CellContent view that fills the row:

struct ContentView: View {
    var body: some View {
        Grid {
            GridRow {
                ForEach(1...5, id: \.self) { index in
                    CellContent(index: index, color: .red)
                }
            }
            
            GridRow {
                ForEach(6...10, id: \.self) { index in
                    CellContent(index: index, color: .blue)
                }
            }
            
            GridRow {
                ForEach(11...15, id: \.self) { index in
                    CellContent(index: index, color: .green)
                }
            }
            
            CellContent(index: 16, color: .blue)
        }
        .padding()
    }
}

Within the Preview panel, the grid should appear as shown in Figure 1-2 below:

Figure 1-2

Automatic Empty Grid Cells

When creating grids, we generally assume that each row must contain the same number of columns. This is not, however, a requirement when using the Grid and GridRow views. When the Grid view is required to display rows containing different cell counts, it will automatically add empty cells to shorter rows so that they match the longest row. To experience this in our example, change the ForEach loop ranges as follows:

.
.
GridRow {
    ForEach(1...5, id: \.self) { index in
        CellContent(index: index, color: .red)
    }
}

GridRow {
    ForEach(6...8, id: \.self) { index in
        CellContent(index: index, color: .blue)
    }
}

GridRow {
    ForEach(11...12, id: \.self) { index in
        CellContent(index: index, color: .green)
    }
}
.
.

When the grid is rendered, it will place empty cells within the rows containing fewer cells as shown in Figure 1-3:

Figure 1-3

Adding Empty Cells

In addition to allowing GridRow to add empty cells, you can also insert empty cells into fixed positions in a grid layout. Empty cells are represented by a Color view configured with the “clear” color value. Applying the .gridCellUnsizedAxes() modifier to the Color view ensures that the empty cell matches the default height and width of the occupied cells. Modify the first grid row in our example so that even-numbered columns contain empty cells:

GridRow {
    ForEach(1...5, id: \.self) { index in
        if (index % 2 == 1) {
            CellContent(index: index, color: .red)
        } else {
            Color.clear
                .gridCellUnsizedAxes([.horizontal, .vertical])
        }
    }
}

Refer to the Live Preview to verify that the empty cells appear in the first row of the grid as illustrated in Figure 1-4:

Figure 1-4

Column Spanning

A key feature of Grid and GridRow is the ability for a single cell to span a specified number of columns. We can achieve this by applying the .gridCellColumns() modifier to individual content cell views within GridRow declarations. Add another row to the grid containing two cells configured to span two and three columns respectively:

.
.
CellContent(index: 16, color: .blue)

GridRow {
    CellContent(index: 17, color: .orange)
        .gridCellColumns(2)
    CellContent(index: 18, color: .indigo)
        .gridCellColumns(3)
}
.
.

The layout will now appear as shown below:

Figure 1-5

Grid Alignment and Spacing

Spacing between rows and columns can be applied using the Grid view’s verticalSpacing and horizontalSpacing parameters, for example:

Grid(horizontalSpacing: 30, verticalSpacing: 0) {
    GridRow {
        ForEach(1...5, id: \.self) { index in
.
.

The above changes increase the spacing between columns while removing the spacing between rows so that the grid appears as shown in the figure below:

Figure 1-6

We designed CellContent view used throughout this chapter to fill the available space within a grid cell. As this makes it impossible to see changes in alignment, we need to add cells containing content that will demonstrate alignment settings. Begin by inserting two new rows at the top of the grid as outlined below. Also, remove the code that placed empty cells in the row containing cells 1 through 5 so that all cells are displayed:

struct ContentView: View {
    var body: some View {
        Grid {

            GridRow {
                CellContent(index: 0, color: .orange)
                Image(systemName: "record.circle.fill")
                Image(systemName: "record.circle.fill")
                Image(systemName: "record.circle.fill")
                CellContent(index: 0, color: .yellow)
                
            }
            .font(.largeTitle)
            
            GridRow {
                CellContent(index: 0, color: .orange)
                Image(systemName: "record.circle.fill")
                Image(systemName: "record.circle.fill")
                Image(systemName: "record.circle.fill")
                CellContent(index: 0, color: .yellow)
                
            }
            .font(.largeTitle)

            GridRow {
                ForEach(1...5, id: \.self) { index in
                        CellContent(index: index, color: .red)
                }
            }
.
.

After making these changes, refer to the preview and verify that the top three rows of the grid match that shown in Figure 1-7:

Figure 1-7

We can see from the positioning of the circle symbols that the Grid and GridRow views default to centering content within grid cells. The default alignment for all cells within a grid can be changed by assigning one of the following values to the alignment parameter of the Grid view:

  • .trailing
  • .leading • .top
  • .bottom
  • .topLeading
  • .topTrailing
  • .bottomLeading
  • .bottomTrailing
  • .center

Cell content can also be aligned with the baselines of text contained in adjoining cells using the following alignment values:

  • .centerFirstTextBaseline
  • .centerLastTextBaseline
  • .leadingFirstTextBaseline
  • .leadingLastTextBaseline
  • .trailingFirstTextBaseline
  • .trailingLastTextBaseline

Modify the Grid declaration in the example code so that all content is aligned at the leading top of the containing cell:

struct ContentView: View {
    var body: some View {
        Grid(alignment: .topLeading) {
.
.

Review the preview panel and confirm that the positioning of the circle symbols matches the layout shown in Figure 1-8:

Figure 1-8

It is also possible to override the default vertical alignment setting on individual rows using the alignment property of the GridRow view. The following code modifications, for example, change the second row of symbols to use bottom alignment:

struct ContentView: View {
    var body: some View {
        Grid(alignment: .topLeading) {
                
        GridRow(alignment: .bottom) {
            CellContent(index: 0, color: .orange)
            Image(systemName: "record.circle.fill")
            Image(systemName: "record.circle.fill")
            Image(systemName: "record.circle.fill")
            CellContent(index: 0, color: .yellow)
            
        }
        .font(.largeTitle)
.
.

The circles in the first row are now positioned along the bottom of the row while the second row continues to adopt the default alignment specified by the parent grid view:

Figure 1-9

Note that GridRow alignment will only adjust the vertical positioning of cell content. As illustrated above, the first row of circles has continued to use the leading alignment applied to the parent Grid view.

Horizontal content alignment for the cells in individual columns can be changed by applying the .gridColumnAlignment() modifier to any cell within the corresponding column. The following code change, for example, applies trailing alignment to the second grid column:

struct ContentView: View {
    var body: some View {
        Grid(alignment: .topLeading) {
                
        GridRow(alignment: .bottom) {
            CellContent(index: 0, color: .orange)
            Image(systemName: "record.circle.fill")
                .gridColumnAlignment(.trailing)
            Image(systemName: "record.circle.fill")
            Image(systemName: "record.circle.fill")
            CellContent(index: 0, color: .yellow)
            
        }
        .font(.largeTitle)
.
.

When previewed, the first grid rows will appear as illustrated in Figure 1-10:

Figure 1-10

Finally, you can override content alignment in an individual using the .gridCellAnchor() modifier as follows:

Grid(alignment: .topLeading) {
        
GridRow(alignment: .bottom) {
    CellContent(index: 0, color: .orange)
    Image(systemName: "record.circle.fill")
        .gridColumnAlignment(.trailing)
    Image(systemName: "record.circle.fill")
        .gridCellAnchor(.center)
    Image(systemName: "record.circle.fill")
        .gridCellAnchor(.top)
    CellContent(index: 0, color: .yellow)  
}
.font(.largeTitle)

Once the preview updates to reflect the above changes, the circle symbol rows should appear as shown below:

Figure 1-11

Summary

The Grid and GridRow views combine to provide highly flexible grid layout options when working with SwiftUI. While these views are unsuitable for displaying scrolling grids containing a large number of views, they have several advantages over the LazyVGrid and LazyHGrid views covered in the previous chapter. Particular strengths include the ability for a single cell to span multiple columns, support for empty cells, automatic addition of empty cells to maintain matching column counts, and the ability to adjust content alignment at the grid, row, and individual cell levels.

 

Integrating SwiftUI with UIKit

Apps developed before the introduction of SwiftUI will have been developed using UIKit and other UIKit-based frameworks included with the iOS SDK. Given the benefits of using SwiftUI for future development, it will be a common requirement to integrate the new SwiftUI app functionality with the existing project code base. Fortunately, this integration can be achieved with relative ease using the UIHostingController.

An Overview of the Hosting Controller

The hosting controller (in the form of the UIHostingController class) is a subclass of UIViewController, the sole purpose of which is to enclose a SwiftUI view so that it can be integrated into an existing UIKit-based project.

Using a hosting view controller, a SwiftUI view can be treated either as an entire scene (occupying the full screen), or as an individual component within an existing UIKit scene layout by embedding a hosting controller in a container view. A container view essentially allows a view controller to be configured as the child of another view controller.

SwiftUI views can be integrated into a UIKit project either from within the code or using an Interface Builder storyboard. The following code excerpt embeds a SwiftUI content view in a hosting view controller and then presents it to the user:

let swiftUIController = 
                   UIHostingController(rootView: SwiftUIView())
present(swiftUIController, animated: true, completion: nil)

The following example, on the other hand, embeds a hosted SwiftUI view directly into the layout of an existing UIViewController:

let swiftUIController = 
             UIHostingController(rootView: SwiftUIView())
 
addChild(swiftUIController)
view.addSubview(swiftUIController.view)
 
swiftUIController.didMove(toParent: self)

In the rest of this chapter, an example project will be created that demonstrates the use of UIHostingController instances to integrate SwiftUI views into an existing UIKit-based project both programmatically and using storyboards.

A UIHostingController Example Project

Unlike previous chapters, the project created in this chapter will create a UIKit Storyboard-based project instead of a SwiftUI Multiplatform app. Launch Xcode and select the iOS tab followed by the App template as shown in Figure 54-1 below:

Figure 54-1

Click the Next button and, on the options screen, name the project HostingControllerDemo and change the Interface menu from SwiftUI to Storyboard. Click the Next button once again and proceed with the project creation process.

Adding the SwiftUI Content View

In the course of building this project, a SwiftUI content view will be integrated into a UIKit storyboard scene using the UIHostingController in three different ways. In preparation for this integration process, a SwiftUI View file needs to be added to the project. Add this file now by selecting the File -> New -> File… menu option and choosing the SwiftUI View template option from the resulting dialog. Proceed through the screens, keeping the default SwiftUIView file name.

With the SwiftUIView.swift file loaded into the editor, modify the declaration so that it reads as follows:

import SwiftUI
 
struct SwiftUIView: View {
    
    var text: String
    
    var body: some View {
        VStack {
            Text(text)
            HStack {
                Image(systemName: "smiley")
                Text("This is a SwiftUI View")
            }
        }
        .font(.largeTitle)
    }
}
 
struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView(text: "Sample Text")
    }
}

With the SwiftUI view added, the next step is to integrate it so that it can be launched as a separate view controller from within the storyboard.

Preparing the Storyboard

Within Xcode, select the Main.storyboard file so that it loads into the Interface Builder tool. As currently configured, the storyboard consists of a single view controller scene as shown in Figure 54-2:

Figure 54-2

So that the user can navigate back to the current scene, the view controller needs to be embedded into a Navigation Controller. Select the current scene by clicking on the View Controller button circled in the figure above so that the scene highlights with a blue outline and select the Editor -> Embed In -> Navigation Controller menu option. At this point the storyboard canvas should resemble Figure 54-3:

Figure 54-3

The first SwiftUI integration will require a button which, when clicked, will show a new view controller containing the SwiftUI View. Display the Library panel by clicking on the button highlighted in Figure 54-4 and locate and drag a Button view onto the view controller scene canvas:

Figure 54-4

Double-click on the button to enter editing mode and change the text so that it reads “Show Second Screen”. To maintain the position of the button it will be necessary to add some layout constraints. Use the Resolve Auto Layout Issues button indicated in Figure 54-5 to display the menu and select the Reset to Suggested Constraints option to add any missing constraints to the button widget:

Figure 54-5

Adding a Hosting Controller

The storyboard is now ready to add a UIHostingController and to implement a segue on the button to display the SwiftUIView layout. Display the Library panel once again, locate the Hosting View Controller and drag and drop it onto the storyboard canvas so that it resembles Figure 54-6 below:

Figure 54-6

Next, add the segue by selecting the “Show Second Screen” button and Ctrl-clicking and dragging to the Hosting Controller:

Figure 54-7

Release the line once it is within the bounds of the hosting controller and select Show from the resulting menu.

Compile and run the project on a simulator or connected device and verify that clicking the button navigates to the hosting controller screen and that the Navigation Controller has provided a back button to return to the initial screen. At this point the hosting view controller appears with a black background indicating that it currently has no content.

Configuring the Segue Action

The next step is to add an IBSegueAction to the segue that will load the SwiftUI view into the hosting controller when the button is clicked. Within Xcode, select the Editor -> Assistant menu option to display the Assistant Editor panel. When the Assistant Editor panel appears, make sure that it is displaying the content of the ViewController.swift file. By default, the Assistant Editor will be in Automatic mode, whereby it automatically attempts to display the correct source file based on the currently selected item in Interface Builder. If the correct file is not displayed, the toolbar along the top of the editor panel can be used to select the correct file.

If the ViewController.swift file is not loaded, begin by clicking on the Automatic entry in the editor toolbar as highlighted in Figure 54-8:

Figure 54-8

From the resulting menu (Figure 54-9), select the ViewController.swift file to load it into the editor:

Figure 54-9

Next, Ctrl-click on the segue line between the initial view controller and the hosting controller and drag the resulting line to a position beneath the viewDidLoad() method in the Assistant panel as shown in Figure 54-10:

Figure 54-10

Release the line and enter showSwiftUIView into the Name field of the connection dialog before clicking the Connect button:

Figure 54-11

Within the ViewController.swift file Xcode will have added the IBSegueAction method which needs to be modified as follows to embed the SwiftUIView layout into the hosting controller (note that the SwiftUI framework also needs to be imported):

import UIKit
import SwiftUI
.
.
@IBSegueAction func showSwiftUIView(_ coder: NSCoder) -> UIViewController? {
    return UIHostingController(coder: coder, 
                rootView: SwiftUIView(text: "Integration One"))
}

Compile and run the app once again, this time confirming that the second screen appears as shown in Figure 54-12:

Figure 54-12

Embedding a Container View

For the second integration, a Container View will be added to an existing view controller scene and used to embed a SwiftUI view alongside UIKit components. Within the Main.storyboard file, display the Library and drag and drop a Container View onto the scene canvas of the initial view controller, then position and size the view so that it appears as shown in Figure 54-13:

Figure 54-13

Before proceeding, click on the background of the view controller scene before using the Resolve Auto Layout Issues button indicated in Figure 54-5 once again and select the Reset to Suggested Constraints option to add any missing constraints to the layout.

Note that Xcode has also added an extra View Controller for the Container View (located above the initial view controller in the above figure). This will need to be replaced by a Hosting Controller so select this controller and tap the keyboard delete key to remove it from the storyboard.

Display the Library, locate the Hosting View Controller and drag and drop it so that it is positioned above the initial view controller in the storyboard canvas. Ctrl-click on the Container View in the view controller scene and drag the resulting line to the new hosting controller before releasing. From the segue menu, select the Embed option:

Figure 54-14

Once the Container View has been embedded in the hosting controller, the storyboard should resemble Figure 54-15:

Figure 54-15

All that remains is to add an IBSegueAction to the connection between the Container View and the hosting controller. Display the Assistant Editor once again, Ctrl-click on the arrow pointing in towards the left side of the hosting controller and drag the line to a position beneath the showSwiftUIView action method. Name the action embedSwiftUIView and click on the Connect button. Once the new method has been added, modify it as follows:

@IBSegueAction func embedSwiftUIView(_ coder: NSCoder) ->
                                         UIViewController? {
    return UIHostingController(coder: coder, rootView: SwiftUIView(text: "Integration Two"))
}

When the app is now run, the SwiftUI view will appear in the initial view controller within the Container View:

Figure 54-16

Embedding SwiftUI in Code

In this, the final integration example, the SwiftUI view will be embedded into the layout for the initial view controller programmatically. Within Xcode, edit the ViewController.swift file, locate the viewDidLoad() method and modify it as follows:

override func viewDidLoad() {
    super.viewDidLoad()
    
    let swiftUIController = UIHostingController(rootView: SwiftUIView(text: "Integration Three"))
 
    addChild(swiftUIController)
    swiftUIController.view.translatesAutoresizingMaskIntoConstraints 
                                                      = false
 
    view.addSubview(swiftUIController.view)
 
    swiftUIController.view.centerXAnchor.constraint(
              equalTo: view.centerXAnchor).isActive = true
    swiftUIController.view.centerYAnchor.constraint(
              equalTo: view.centerYAnchor).isActive = true
 
    swiftUIController.didMove(toParent: self)
}

The code begins by creating a UIHostingController instance containing the SwiftUIView layout before adding it as a child to the current view controller. The translates autoresizing property is set to false so that any constraints we add will not conflict with the automatic constraints usually applied when a view is added to a layout. Next, the UIView child of the UIHostingController is added as a subview of the containing view controller’s UIView. Constraints are then set on the hosting view controller to position it in the center of the screen. Finally, an event is triggered to let UIKit know that the hosting controller has been moved to the container view controller. Run the app one last time and confirm that it appears as shown in Figure 54-17:

Figure 54-17

Summary

Any apps developed before the introduction of SwiftUI will have been created using UIKit. While it is certainly possible to continue using UIKit when enhancing and extending an existing app, it probably makes more sense to use SwiftUI when adding new app features (unless your app needs to run on devices that do not support iOS 13 or newer). Recognizing the need to integrate new SwiftUI-based views and functionality with existing UIKit code, Apple created the UIHostingViewController. This controller is designed to wrap SwiftUI views in a UIKit view controller that can be integrated into existing UIKit code. As demonstrated in this chapter, the hosting controller can be used to integrate SwiftUI and UIKit both within storyboards and programmatically within code. Options are available to integrate entire SwiftUI user interfaces in independent view controllers or, through the use of container views, to embed SwiftUI views alongside UIKit views within an existing layout.

Integrating UIViewControllers with SwiftUI

The previous chapter outlined how to integrate UIView based components into SwiftUI using the UIViewRepresentable protocol. This chapter will focus on the second option for combining SwiftUI and UIKit within an iOS project in the form of UIViewController integration.

UIViewControllers and SwiftUI

The UIView integration outlined in the previous chapter is useful for integrating either individual or small groups of UIKit-based components with SwiftUI. Existing iOS apps are likely to consist of multiple ViewControllers, each representing an entire screen layout and functionality (also referred to as scenes). SwiftUI allows entire view controller instances to be integrated via the UIViewControllerRepresentable protocol. This protocol is similar to the UIViewRepresentable protocol and works in much the same way with the exception that the method names are different.

The remainder of this chapter will work through an example that demonstrates the use of the UIViewControllerRepresentable protocol to integrate a UIViewController into SwiftUI.

Creating the ViewControllerDemo project

For the purposes of an example, this project will demonstrate the integration of the UIImagePickerController into a SwiftUI project. This is a class that is used to allow the user to browse and select images from the device photo library and for which there is currently no equivalent within SwiftUI.

Just like custom built view controllers in an iOS app UIImagePickerController is a subclass of UIViewController so can be used with UIViewControllerRepresentable to integrate into SwiftUI. Begin by launching Xcode and creating a new Multiplatform App project named ViewControllerDemo.

Wrapping the UIImagePickerController

With the project created, it is time to create a new SwiftUI View file to contain the wrapper that will make the UIPickerController available to SwiftUI. Create this file by right-clicking on the Shared folder item in the project navigator panel, selecting the New File… menu option and creating a new file named MyImagePicker using the SwiftUI View file template.

Once the file has been created, delete the current content and modify the file so that it reads as follows:

import SwiftUI
 
struct MyImagePicker: UIViewControllerRepresentable {
 
    func makeUIViewController(context: 
              UIViewControllerRepresentableContext<MyImagePicker>) -> 
                      UIImagePickerController {
        let picker = UIImagePickerController()
        return picker
    }
 
    func updateUIViewController(_ uiViewController: 
            UIImagePickerController, context: 
              UIViewControllerRepresentableContext<MyImagePicker>) {
 
    }
}
 
struct MyImagePicker_Previews: PreviewProvider {
    static var previews: some View {
        MyImagePicker()
    }
}

If Xcode reports that UIViewControllerRepresentable is undefined, make sure that you have selected an iOS device or simulator as the run target in the toolbar.

Click on the Live Preview button in the canvas to test that the image picker appears as shown in Figure 53-1 below:

Figure 53-1

Designing the Content View

When the project is complete, the content view will display an Image view and a button contained in a VStack. This VStack will be embedded in a ZStack along with an instance of the MyImagePicker view. When the button is clicked, the MyImagePicker view will be made visible over the top of the VStack from which an image may be selected. Once the image has been selected, the image picker will be hidden from view and the selected image displayed on the Image view.

To make this work, two state property variables will be used, one for the image to be displayed and the other a Boolean value to control whether or not the image picker view is currently visible. Bindings for these two variables will be declared in the MyPickerView structure so that changes within the view controller are reflected within the main content view. With these requirements in mind, load the ContentView.swift file into the editor and modify it as follows:

struct ContentView: View {
    
    @State var imagePickerVisible: Bool = false
    @State var selectedImage: Image? = Image(systemName: "photo")
 
    var body: some View {
        ZStack {
            VStack {
                
                selectedImage?
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    
                Button(action: {
                    withAnimation {
                        self.imagePickerVisible.toggle()
                    }
                }) {
                    Text("Select an Image")
                }
                
            }.padding()
            
            if (imagePickerVisible) {
                MyImagePicker()
            }
        }
    }
}
.
.

Once the changes have been made, the preview for the view should resemble Figure 53-2:

Figure 53-2

Test the view using Live Preview and make sure that clicking on the “Select an Image” button causes the MyPickerView to appear. Note that selecting an image or clicking on the Cancel button does not dismiss the picker. To implement this behavior, some changes are needed within the MyImagePicker declaration.

Completing MyImagePicker

A few remaining tasks now need to be completed within the MyImagePicker.swift file. First, bindings to the two ContentView state properties need to be declared:

struct MyImagePicker: UIViewControllerRepresentable {
 
    @Binding var imagePickerVisible: Bool
    @Binding var selectedImage: Image?
.
.

Next, a coordinator needs to be implemented to act as the delegate for the UIImagePickerView instance. This will require that the coordinator class conform to both the UINavigationControllerDelegate and UIImagePickerControllerDelegate protocols. The coordinator will need to receive notification when an image is picked, or the user taps the cancel button so the imagePickerControllerDidCancel and didFinishPickingMediaWithInfo delegate methods will both need to be implemented.

In the case of the imagePickerControllerDidCancel method, the imagePickerVisible state property will need to be set to false. This will result in a state change within the content view causing the image picker to be removed from view.

The didFinishPickingMediaWithInfo method, on the other hand, will be passed the selected image which it will need to assign to the currentImage property before also setting the imagePickerVisible property to false.

The coordinator will also need local copies of the state property bindings. Bringing these requirements together results in a coordinator which reads as follows:

class Coordinator: NSObject, UINavigationControllerDelegate, 
                     UIImagePickerControllerDelegate {
 
    @Binding var imagePickerVisible: Bool
    @Binding var selectedImage: Image?
 
    init(imagePickerVisible: Binding<Bool>, 
                      selectedImage: Binding<Image?>) {
        _imagePickerVisible = imagePickerVisible
        _selectedImage = selectedImage
    }
 
    func imagePickerController(_ picker: UIImagePickerController,
                               didFinishPickingMediaWithInfo 
                info: [UIImagePickerController.InfoKey : Any]) {
        let uiImage = 
            info[UIImagePickerController.InfoKey.originalImage] as!    
                                                               UIImage
        selectedImage = Image(uiImage: uiImage)
        imagePickerVisible = false
    }
 
    func imagePickerControllerDidCancel(_ 
                        picker: UIImagePickerController) {
        imagePickerVisible = false
    }
}

Remaining in the MyPickerView.swift file, add the makeCoordinator() method, remembering to pass through the two state property bindings:

func makeCoordinator() -> Coordinator {
    return Coordinator(imagePickerVisible: $imagePickerVisible, 
                            selectedImage: $selectedImage)
}

Finally, modify the makeUIVewController() method to assign the coordinator as the delegate and comment out the preview structure to remove the remaining syntax errors:

func makeUIViewController(context: 
        UIViewControllerRepresentableContext<MyImagePicker>) ->  
                 UIImagePickerController {
    let picker = UIImagePickerController()
    picker.delegate = context.coordinator
    return picker
}
.
.
/*
struct MyImagePicker_Previews: PreviewProvider {
    static var previews: some View {
        MyImagePicker()
    }
}
*/

Completing the Content View

The final task before testing the app is to modify the Content View so that the two state properties are passed through to the MyImagePicker instance. Edit the ContentView.swift file and make the following modifications:

struct ContentView: View {
    
    @State var imagePickerVisible: Bool = false
    @State var selectedImage: Image? = Image(systemName: "photo")
 
    var body: some View {
.
.
        if (imagePickerVisible) {
                MyImagePicker(imagePickerVisible:    
                        $imagePickerVisible, 
                           selectedImage: $selectedImage)
        }
.
.

Testing the App

With the ContentView.swift file still loaded into the editor, enable Live Preview mode and click on the “Select an Image” button. When the picker view appears, navigate to and select an image. When the image has been selected, the picker view should disappear to reveal the selected image displayed on the Image view:

Figure 53-3

Click the image selection button once again, this time testing that the Cancel button dismisses the image picker without changing the selected image.

Summary

In addition to allowing for the integration of individual UIView based objects into SwiftUI projects, it is also possible to integrate entire UIKit view controllers representing entire screen layouts and functionality. View controller integration is similar to working with UIViews, involving wrapping the view controller in a structure conforming to the UIViewControllerRepresentable protocol and implementing the associated methods. As with UIView integration, delegates and data sources for the view controller are handled using a Coordinator instance.

Integrating UIViews with SwiftUI

Prior to the introduction of SwiftUI, all iOS apps were developed using UIKit together with a collection of UIKit-based supporting frameworks. Although SwiftUI is provided with a wide selection of components with which to build an app, there are instances where there is no SwiftUI equivalent to options provided by the other frameworks.

Given the quantity of apps that were developed before the introduction of SwiftUI it is also important to be able to integrate existing non-SwiftUI functionality with SwiftUI development projects and vice versa. Fortunately, SwiftUI includes several options to perform this type of integration.

SwiftUI and UIKit Integration

Before looking in detail at integrating SwiftUI and UIKit it is worth taking some time to explore whether a new app project should be started as a UIKit or SwiftUI project, and whether an existing app should be migrated entirely to SwiftUI. When making this decision, it is important to remember that apps containing SwiftUI code can only be used on devices running iOS 13 or later.

If you are starting a new project, then the best approach may be to build it as a SwiftUI project (support for older iOS versions not withstanding) and then integrate with UIKit when required functionality is not provided directly by SwiftUI. Although Apple continues to enhance and support the UIKit way of developing apps, it is clear that Apple sees SwiftUI as the future of app development. SwiftUI also makes it easier to develop and deploy apps for iOS, macOS, tvOS, iPadOS and watchOS without making major code changes.

If, on the other hand, you have existing projects that pre-date the introduction of SwiftUI then it probably makes sense to leave the existing code unchanged, build any future additions to the project using SwiftUI and to integrate those additions into your existing code base.

SwiftUI provides three options for performing integrations of these types. The first, and the topic of this chapter, is to integrate individual UIKit-based components (UIViews) into SwiftUI View declarations.

For those unfamiliar with UIKit, a screen displayed within an app is typically implemented using a view controller (implemented as an instance of UIViewController or a subclass thereof). The subject of integrating view controllers into SwiftUI will be covered in the chapter entitled Integrating UIViewControllers with SwiftUI.

Finally, SwiftUI views may also be integrated into existing UIKit-based code, a topic which will be covered in the chapter entitled Integrating SwiftUI with UIKit.

Integrating UIViews into SwiftUI

The individual components that make up the user interface of a UIKit-based application are derived from the UIView class. Buttons, labels, text views, maps, sliders and drawings (to name a few) are all ultimately subclasses of the UIKit UIView class.

To facilitate the integration of a UIView based component into a SwiftUI view declaration, SwiftUI provides the UIViewRepresentable protocol. To integrate a UIView component into SwiftUI, that component needs to be wrapped in a structure that implements this protocol.

At a minimum the wrapper structure must implement the following methods to comply with the UIViewRepresentable protocol:

  • makeUIView() – This method is responsible for creating an instance of the UIView-based component, performing any necessary initialization and returning it.
  • updateView() – Called each time a change occurs within the containing SwiftUI view that requires the UIView to update itself.

The following optional method may also be implemented:

  • dismantleUIView() – Provides an opportunity to perform cleanup operations before the view is removed.

As an example, assume that there is a feature of the UILabel class that is not available with the SwiftUI Text view. To wrap a UILabel view using UIViewRepresentable so that it can be used within SwiftUI, the structure might be implemented as follows:

import SwiftUI
 
struct MyUILabel: UIViewRepresentable {
    
    var text: String
    
    func makeUIView(context: UIViewRepresentableContext<MyUILabel>) 
                             -> UILabel {
        let myLabel = UILabel()
        myLabel.text = text
        return myLabel
    }
    
    func updateUIView(_ uiView: UILabel, 
                    context: UIViewRepresentableContext<MyUILabel>) {
        // Perform any update tasks if necessary
    }
}
 
struct MyUILabel_Previews: PreviewProvider {
    static var previews: some View {
        MyUILabel(text: "Hello")
    }
}

With the UILabel view wrapped, it can now be referenced within SwiftUI as though it is a built-in SwiftUI component:

struct ContentView: View {
    var body: some View {
        
        VStack {
            MyUILabel(text: "Hello UIKit")
        }
    }
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Obviously, UILabel is a static component that does not need to handle any user interaction events. For views that need to respond to events, however, the UIViewRepresentable wrapper needs to be extended to implement a coordinator.

Adding a Coordinator

A coordinator takes the form of a class that implements the protocols and handler methods required by the wrapped UIView component to handle events. An instance of this class is then applied to the wrapper via the makeCoordinator() method of the UIViewRepresentable protocol.

As an example, consider the UIScrollView class. This class has a feature whereby a refresh control (UIRefreshControl) may be added such that when the user attempts to scroll beyond the top of the view, a spinning progress indicator appears and a method called allowing the view to be updated with the latest content. This is a common feature used by news apps to allow the user to download the latest news headlines. Once the refresh is complete, this method needs to call the endRefreshing() method of the UIRefreshControl instance to remove the progress spinner.

Clearly, if the UIScrollView is to be used with SwiftUI, there needs to be a way for the view to be notified that the UIRefreshControl has been triggered and to perform the necessary steps.

The Coordinator class for a wrapped UIScrollView with an associated UIRefreshControl object would be implemented as follows:

class Coordinator: NSObject {
    var control: MyScrollView
 
    init(_ control: MyScrollView) {
        self.control = control
    }
    
    @objc func handleRefresh(sender: UIRefreshControl) {
        sender.endRefreshing()
    }
}

In this case the initializer for the coordinator is passed the current UIScrollView instance, which it stores locally. The class also implements a function named handleRefresh() which calls the endRefreshing() method of the scrolled view instance.

An instance of the Coordinator class now needs to be created and assigned to the view via a call to the makeCoordinator() method as follows:

func makeCoordinator() -> Coordinator {
     Coordinator(self)
}

Finally, the makeUIView() method needs to be implemented to create the UIScrollView instance, configure it with a UIRefreshControl and to add a target to call the handleRefresh() method when a value changed event occurs on the UIRefreshControl instance:

func makeUIView(context: Context) -> UIScrollView {
    let scrollView = UIScrollView()
    scrollView.refreshControl = UIRefreshControl()
    
    scrollView.refreshControl?.addTarget(context.coordinator, 
            action: #selector(Coordinator.handleRefresh),
                                      for: .valueChanged)
    
    return scrollView
}

Handling UIKit Delegation and Data Sources

Delegation is a feature of UIKit that allows an object to pass the responsibility for performing one or more tasks on to another object and is another area in which extra steps may be necessary if events are to be handled by a wrapped UIView.

The UIScrolledView, for example, can be assigned a delegate which will be notified when certain events take place such as the user performing a scrolling motion or when the user scrolls to the top of the content. The delegate object will need to conform to the UIScrolledViewDelegate protocol and implement the specific methods that will be called automatically when corresponding events take place in the scrolled view.

Similarly, a data source is an object which provides a UIView based component with data to be displayed. The UITableView class, for example, can be assigned a data source object to provide the cells to be displayed in the table. This data object must conform with the UITableViewDataSource protocol.

To handle delegate events when integrating UIViews into SwiftUI, the coordinator class needs to be declared as implementing the appropriate delegate protocol and must include the callback methods for any events of interest to the scrolled view instance. The coordinator must then be assigned as the delegate for the UIScrolledView instance. The previous coordinator implementation can be extended to receive notification that the user is currently scrolling as follows:

class Coordinator: NSObject, UIScrollViewDelegate {
    var control: MyScrollView
 
    init(_ control: MyScrollView) {
        self.control = control
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // User is currently scrolling
    }
    
    @objc func handleRefresh(sender: UIRefreshControl) {
        sender.endRefreshing()
    }
}

The makeUIView() method must also be modified to access the coordinator instance (which is accessible via the representable context object passed to the method) and add it as the delegate for the UIScrolledView instance:

func makeUIView(context: Context) -> UIScrollView {
    let scrollView = UIScrollView()
    scrollView.delegate = context.coordinator
.
.

In addition to providing access to the coordinator, the context also includes an environment property which can be used to access both the SwiftUI environment and any @EnvironmentObject properties declared in the SwiftUI view. Now, while the user is scrolling, the scrollViewDidScroll delegate method will be called repeatedly.

An Example Project

The remainder of this chapter will work through the creation of a simple project that demonstrates the use of the UIViewRepresentable protocol to integrate a UIScrolledView into a SwiftUI project. Begin by launching Xcode and creating a new SwiftUI Multiplatform App project named UIViewDemo.

Wrapping the UIScrolledView

The first step in the project is to use the UIViewRepresentable protocol to wrap the UIScrollView so that it can be used with SwiftUI. Right-click on the Shared folder entry in the project navigator panel, select the New File… menu option and create a new file named MyScrollView using the SwiftUI View template.

With the new file loaded into the editor, delete the current content and modify it so it reads as follows:

import SwiftUI
 
struct MyScrollView: UIViewRepresentable {
    
    var text: String
    
    func makeUIView(context: UIViewRepresentableContext<MyScrollView>)
               -> UIScrollView {
        let scrollView = UIScrollView()
        scrollView.refreshControl = UIRefreshControl()
        let myLabel = UILabel(frame:
                   CGRect(x: 0, y: 0, width: 300, height: 50))
        myLabel.text = text
        scrollView.addSubview(myLabel)
        return scrollView
    }
    
    func updateUIView(_ uiView: UIScrollView,
        context: UIViewRepresentableContext<MyScrollView>) {
        
    }
 
}
 
struct MyScrollView_Previews: PreviewProvider {
    static var previews: some View {
        MyScrollView(text: "Hello World")
    }
}

If the above code generates syntax errors, make sure that an iOS device is selected as the run target in the Xcode toolbar instead of macOS. Use the Live Preview to build and test the view so far. Once the Live Preview is active and running, click and drag downwards so that the refresh control appears as shown in Figure 52-1:

Figure 52-1

Release the mouse button to stop the scrolling and note that the refresh indicator remains visible because the event is not being handled. Clearly, it is now time to add a coordinator.

struct MyScrollView: UIViewRepresentable {
.
.
    func updateUIView(_ uiView: UIScrollView, context: UIViewRepresentableContext<MyScrollView>) {
        
    }
 
    class Coordinator: NSObject, UIScrollViewDelegate {
        var control: MyScrollView
 
        init(_ control: MyScrollView) {
            self.control = control
        }
        
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            print("View is Scrolling")
        }
        
        @objc func handleRefresh(sender: UIRefreshControl) {
            sender.endRefreshing()
        }
    }
}

Implementing the Coordinator

Remaining within the MyScrollView.swift file, add the coordinator class declaration so that it reads as follows:

Next, modify the makeUIView() method to add the coordinator as the delegate and add the handleRefresh() method as the target for the refresh control:

func makeUIView(context: Context) -> UIScrollView {
    let scrollView = UIScrollView()
    scrollView.delegate = context.coordinator
    
    scrollView.refreshControl = UIRefreshControl()
    scrollView.refreshControl?.addTarget(context.coordinator, action:
        #selector(Coordinator.handleRefresh),
                                      for: .valueChanged)
.
.
    return scrollView
}

Finally, add the makeCoordinator() method so that it reads as follows:

func makeCoordinator() -> Coordinator {
     Coordinator(self)
}

Before proceeding, test that the changes work by right-clicking on the Live Preview button in the preview canvas panel and selecting the Debug Preview option from the resulting menu (it may be necessary to stop the Live Preview first). Once the preview is running in debug mode, make sure that the refresh indicator now goes away when downward scrolling stops and that the “View is scrolling” diagnostic message appears in the console while scrolling is in effect.

Using MyScrollView

The final step in this example is to check that MyScrollView can be used from within SwiftUI. To achieve this, load the ContentView.swift file into the editor and modify it so that it reads as follows:

.
.
struct ContentView: View {
    var body: some View {
        MyScrollView(text: "UIView in SwiftUI")
    }
}
.
.

Use Live Preview to test that the view works as expected.

Summary

SwiftUI includes several options for integrating with UIKit-based views and code. This chapter has focused on integrating UIKit views into SwiftUI. This integration is achieved by wrapping the UIView instance in a structure that conforms to the UIViewRepresentable protocol and implementing the makeUIView() and updateView() methods to initialize and manage the view while it is embedded in a SwiftUI layout. For UIKit objects that require a delegate or data source, a Coordinator class needs to be added to the wrapper and assigned to the view via a call to the makeCoordinator() method.