我的專案中有三個視圖 - ContentView、SecondView、ThirdView

我想從 contentView 導航到 secondView,從 secondView 導航到 thirdView。
內容視圖:-
import SwiftUI
struct ContentView: View {
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
Button {
path.append("SecondView")
} label: {
Text("This is the first view")
}
.navigationDestination(for: String.self) { view2 in
if view2 == "SecondView" {
SecondView()
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
第二視圖:-
import SwiftUI
struct SecondView: View {
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
Button {
path.append("ThirdView")
} label: {
Text("This is the second view")
}
.navigationDestination(for: String.self) { view2 in
if view2 == "ThirdView" {
ThirdView()
}
}
}
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
NavigationStack {
SecondView()
}
}
}
第三視圖:-
import SwiftUI
struct ThirdView: View {
var body: some View {
Text("This is the third view")
}
}
struct ThirdView_Previews: PreviewProvider {
static var previews: some View {
NavigationStack {
ThirdView()
}
}
}
怎么了 :-
每當我點擊 ContentView 中的“這是第一個視圖”按鈕時,我都會導航到 SecondView 并自動導航回 contentView。
我想要的是 :-
我想從 contentView 導航到 secondView,從 secondView 導航到 thirdView。
uj5u.com熱心網友回復:
您不應該NavigationStack在層次結構中有多個 s。你應該有一個并通過pathvia a Binding。
struct ContentView: View {
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
Button {
path.append("SecondView")
} label: {
Text("This is the first view")
}
.navigationDestination(for: String.self) { view in
switch view {
case "SecondView":
SecondView(path: $path)
case "ThirdView":
ThirdView()
default:
Text("Unknown")
}
}
}
}
}
struct SecondView: View {
@Binding var path: NavigationPath
var body: some View {
Button {
path.append("ThirdView")
} label: {
Text("This is the second view")
}
}
}
struct ThirdView: View {
var body: some View {
Text("This is the third view")
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
NavigationStack {
SecondView(path: .constant(NavigationPath()))
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/536708.html
