Displaying hierarchical content in expanding lists
An expanding list helps display hierarchical content in expandable sections. This expanding ability can be achieved by creating a struct
that holds some information and an optional array of items. Let's examine how expanding lists work by creating an app that displays the contents of a backpack.
Getting ready
Create a new SwiftUI project named ExpandingLists
.
How to do it…
We'll start by creating a Backpack
struct that describes the properties of the data we want to display. The backpack will conform to the Identifiable
protocol, and each backpack will have a name
, an icon
, an id
, and some content
of the Backpack
type.
A struct
that represents a backpack is good for demonstrating hierarchies because, in real life, you can put a backpack in another backpack. The steps for this recipe are as follows:
- At the top of our
ContentView.swift
file, before theContentView
struct, define theBackpack
struct...