gpt4 book ai didi

SwiftUI - 当第 1 个 DetailView 使用 navigationView 返回 MasterView 时如何自动推送第 2 个 DetailView

转载 作者:行者123 更新时间:2023-11-30 10:31:21 25 4
gpt4 key购买 nike

我是新手

我的xcode版本是11.2.1,swift是5.1.2

<小时/>

当我在MasterView中使用NavigationView时,我有两个DetailView

我想在第一个DetailView关闭时自动进入第二个DetailView

<小时/>

这是我的方法,但失败了。

每当我进入第二个 DetailView 时,

立即自动返回MasterView

/image/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”

但我不知道为什么

请帮帮我,谢谢

抱歉我的英语很差

最佳答案

尝试下面的代码。 (请在真机上测试)

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")
}
}
}
}
}

详细 View 1

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")
}
})
}
}

详细 View 2

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")
}
})
}
}

关于SwiftUI - 当第 1 个 DetailView 使用 navigationView 返回 MasterView 时如何自动推送第 2 个 DetailView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59149637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com