我的项目中有三个视图- 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。
1条答案
按热度按时间r6hnlfcb1#
层次结构中不应该有多个
NavigationStack
。应该有 * 一个 *,并通过Binding
传递path
。