Create a Split View in SwiftUI
Written by Team Kodeco
The NavigationSplitView
in SwiftUI provides a more flexible and robust tool for displaying two or three different views side-by-side. It is typically used as the root view in a scene.
For an example, let’s present a list of animals alongside their detailed views using NavigationSplitView
:
struct Animal: Hashable {
let name: String
let description: String
}
struct ContentView: View {
let animals = [
Animal(name: "Coyote", description: "The coyote is a species of canine native to North America..."),
Animal(name: "Gila Monster", description: "The Gila Monster is a species of venomous lizard native to the southwestern United States..."),
Animal(name: "Roadrunner", description: "The roadrunner is a fast-running bird found in the southwestern United States and Mexico...")
]
@State private var selectedAnimal: (Animal)? = nil
var body: some View {
NavigationSplitView {
List(animals, id: \.name, selection: $selectedAnimal) { animal in
NavigationLink(animal.name, value: animal)
}
.navigationTitle("Arizona Animals")
} detail: {
DetailView(animal: selectedAnimal ?? animals[0])
}
}
}
struct DetailView: View {
let animal: Animal
var body: some View {
VStack {
Text(animal.name)
.font(.largeTitle)
Text(animal.description)
.font(.body)
}
.padding()
.navigationTitle("Animal Details")
}
}
Ensure you’re using an iPad as the simulator and your preview should look like this:
Here’s a brief breakdown of the code:
-
struct Animal: Hashable
: Defines a structure to hold an animal’s name and description. This structure conforms to theHashable
protocol, which enables it to be used with SwiftUI’sList
view. -
@State private var selectedAnimal: (Animal)? = nil
: A state variable that holds the currently selected animal. It’s initially set tonil
. -
NavigationSplitView
: A SwiftUI view that allows for the creation of a two or three-column navigation interface. -
List(animals, id: \.name, selection: $selectedAnimal) { animal in NavigationLink(animal.name, value: animal) }
: A list view that displays each animal’s name. The list’sselection
binding is connected to theselectedAnimal
state variable. When an animal is selected in the list,selectedAnimal
is updated. -
DetailView(animal: selectedAnimal ?? animals[0])
: The detail view displays information about the currently selected animal. If no animal is selected (i.e.,selectedAnimal
isnil
), it defaults to the first animal in the list. -
struct DetailView: View {...
: Similar to the previous example, this view displays the details of a selected animal.
The NavigationSplitView
will automatically create a split view layout on iPad and Mac devices, presenting the master and detail views side-by-side. This makes the creation of split views in SwiftUI even more seamless and effective, adding a lot of flexibility to your apps.