我想做一个按钮直接进入根视图
所以我找到了解决方案并应用了
SwiftUI: How to pop to Root view
但是,它在父子之间的 1:1 连接中运行良好,
如果有两个或多个子视图,则无法正常工作。
您可以从 ContentView 转到两个子视图(View2、View2_1)。
但是,当您按下按钮转到 2 时,有时会转到 2,有时会转到 2_1。
我想去我想去的景色。
import SwiftUI
struct ContentView: View {
@State var isActive : Bool = false
var body: some View {
NavigationView {
VStack{
NavigationLink(
destination: ContentView2(rootIsActive: self.$isActive),
isActive: self.$isActive
) {
Text(" go -> 2!")
}
.isDetailLink(false)
.navigationBarTitle("Root")
NavigationLink(
destination: ContentView2_1(rootIsActive: self.$isActive),
isActive: self.$isActive
) {
Text("go -> 2_1 !")
}
.isDetailLink(false)
.navigationBarTitle("Root")
}
}
}
}
struct ContentView2: View {
@Binding var rootIsActive : Bool
var body: some View {
NavigationLink(destination: ContentView3(shouldPopToRootView: self.$rootIsActive)) {
Text("Hello, World #2!")
}
.isDetailLink(false)
.navigationBarTitle("Two")
.navigationBarItems(trailing: Button(action: {
self.rootIsActive = false
}) {
Image(systemName: "house.fill")
})
}
}
struct ContentView2_1: View {
@Binding var rootIsActive : Bool
var body: some View {
NavigationLink(destination: ContentView3(shouldPopToRootView: self.$rootIsActive)) {
Text("Hello, World #2_1!")
}
.isDetailLink(false)
.navigationBarTitle("Two_1")
.navigationBarItems(trailing: Button(action: {
self.rootIsActive = false
}) {
Image(systemName: "house.fill")
})
}
}
struct ContentView3: View {
@Binding var shouldPopToRootView : Bool
var body: some View {
VStack {
Text("Hello, World #3!")
Button (action: { self.shouldPopToRootView = false } ){
Text("Pop to root")
}
}.navigationBarTitle("Three")
.navigationBarItems(trailing: Button(action: {
self.shouldPopToRootView = false
}) {
Image(systemName: "house.fill")
})
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}