Complete the code to create a NavigationStack in SwiftUI.
var body: some View {
[1] {
Text("Home Screen")
}
}The NavigationStack is the modern container for navigation in SwiftUI, replacing NavigationView.
Complete the code to push a new view when a button is tapped inside a NavigationStack.
NavigationStack {
NavigationLink(destination: [1]) {
Text("Go to Detail")
}
}The destination parameter of NavigationLink expects a view instance, like DetailView().
Fix the error in the code to correctly bind the navigation path state.
struct ContentView: View {
@State private var path = [String]()
var body: some View {
NavigationStack(path: [1]) {
List {
Button("Add Item") {
path.append("Item 1")
}
}
.navigationDestination(for: String.self) { item in
Text(item)
}
}
}
}The NavigationStack expects a binding to the path state, so use $path.
Fill both blanks to create a navigationDestination modifier for Int type and show the number.
NavigationStack {
List(1...3, id: \.self) { number in
NavigationLink(value: number) {
Text("Number \(number)")
}
}
.navigationDestination(for: [1]) { value in
Text("Selected: \(value)")
}
}The navigationDestination modifier must match the type used in NavigationLink's value, here Int.
Fill all three blanks to declare a NavigationStack with a path state, push a view, and bind the path.
struct ContentView: View {
@State private var [1] = [String]()
var body: some View {
[2](path: [3]) {
Button("Go") {
[1].append("Next")
}
.navigationDestination(for: String.self) { value in
Text(value)
}
}
}
}Declare a state variable path, use NavigationStack with binding $path to manage navigation.