To finish this program we’re going to make a third and final view to display astronaut details, which will be reached by tapping one of the astronauts in the mission view. This should mostly just be practice for you, but I hope it also shows you the importance of NavigationStack
– we’re digging deeper into our app’s information, and the presentation of views sliding in and out really drives that home to the user.
Start by making a new SwiftUI view called AstronautView
. This will have a single Astronaut
property so it knows what to show, then it will lay that out using a similar ScrollView
/VStack
combination as we had in MissionView
. Give it this code:
struct AstronautView: View {
let astronaut: Astronaut
var body: some View {
ScrollView {
VStack {
Image(astronaut.id)
.resizable()
.scaledToFit()
Text(astronaut.description)
.padding()
}
}
.background(.darkBackground)
.navigationTitle(astronaut.name)
.navigationBarTitleDisplayMode(.inline)
}
}
Once again we need to update the preview so that it creates its view with some data:
#Preview {
let astronauts: [String: Astronaut] = Bundle.main.decode("astronauts.json")
return AstronautView(astronaut: astronauts["aldrin"]!)
.preferredColorScheme(.dark)
}
Now we can present that from the NavigationLink
inside MissionView
. This points to Text("Astronaut details")
right now, but we can update it to point to our new AstronautView
instead:
AstronautView(astronaut: crewMember.astronaut)
That was easy, right? But if you run the app now you’ll see how natural it makes our user interface feel – we start at the broadest level of information, showing all our missions, then tap to select one specific mission, then tap to select one specific astronaut. iOS takes care of animating in the new views, but also providing back buttons and swipes to return to previous views.
SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Link copied to your pasteboard.