我是新手
我的xcode版本是11.2.1,而swift是5.1.2
当我在MasterView中使用NavigationView时,我有两个DetailViews
我要在第一个DetailView关闭时自动输入第二个DetailView
这是我的方法,但失败了。
每当我输入第二个DetailView时,
它将立即自动返回到MasterView
https://i.stack.imgur.com/9voJA.gif
这是我的代码
struct MasterView: View {
@State var tag: Int? = nil
var body: some View {
NavigationView{
VStack{
NavigationLink(destination: DetailView1(tag: self.$tag), tag: 1, selection: self.$tag) {
EmptyView()
}
NavigationLink(destination: DetailView2(tag: self.$tag), tag: 2, selection: self.$tag) {
EmptyView()
}
Button(action: {
self.tag = 1
}) {
Text("press here to enter DetailView1")
}
}
}
}
}
struct DetailView1: View {
@Binding var tag: Int?
var body: some View {
VStack{
Text("DetailView 1")
}
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading:
Button(action: {
self.tag = 2
}) {
HStack {
Image(systemName: "arrow.left.circle")
Text("Go Back")
}
})
}
}
struct DetailView2: View {
@Binding var tag: Int?
var body: some View {
VStack{
Text("DetailView 2 2 2 2 2 2 2")
}
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading:
Button(action: {
self.tag = nil // never execute
}) {
HStack {
Image(systemName: "arrow.left.circle")
Text("Go Back")
}
})
}
}
我发现关闭第一个DetailView时,“ tag”变量将自动设置为“ nil”
但我不知道为什么
请帮助我,谢谢
对不起,我的英语不好
答案 0 :(得分:0)
尝试以下代码。 (请在真实设备中测试)
MasterView
struct MasterView: View {
@State var tag1: Int? = nil
@State var tag2: Int? = nil
var body: some View {
NavigationView{
VStack{
NavigationLink(destination: DetailView1(tag: self.$tag2), tag: 1, selection: self.$tag1) {
EmptyView()
}
NavigationLink(destination: DetailView2(tag: self.$tag2), tag: 2, selection: self.$tag2) {
EmptyView()
}
Button(action: {
self.tag1 = 1
}) {
Text("press here to enter DetailView1")
}
}
}
}
}
DetailView1
struct DetailView1: View {
@Binding var tag: Int?
@Environment(\.presentationMode) var presentation
var body: some View {
VStack{
Text("DetailView -> 1")
}
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading:
Button(action: {
self.tag = 2
self.presentation.wrappedValue.dismiss()
}) {
HStack {
Image(systemName: "arrow.left.circle")
Text("Go Back")
}
})
}
}
DetailView2
struct DetailView2: View {
@Binding var tag: Int?
@Environment(\.presentationMode) var presentation
var body: some View {
VStack{
Text("DetailView -> 2")
}
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading:
Button(action: {
self.tag = nil
self.presentation.wrappedValue.dismiss()
}) {
HStack {
Image(systemName: "arrow.left.circle")
Text("Go Back")
}
})
}
}