如何检查导航堆栈上是否有屏幕?

时间:2020-10-03 22:07:32

标签: swiftui

给出这个...

NavigationLink(destination: Text("Hello")) {
   Text("Press")
}

这...

.sheet(isPresented: $viewModel.showComplete) {
   Text("Hello")
}

如何仅在NavigationLink打开的视图当前不存在的情况下才能打开工作表?

1 个答案:

答案 0 :(得分:1)

您可以访问NavigationLink的isActive参数,并在自定义绑定中使用它来确定是否打开工作表。

这是一个简单的演示:

struct ContentView: View {
    @State var showSheet = false
    @State var linkActive = false
    
    var binding: Binding<Bool> {
        .init(get: {
            showSheet && !linkActive
        }, set: {
            showSheet = $0
        })
    }

    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(
                    destination: DetailView(showSheet: $showSheet),
                    isActive: $linkActive
                ) {
                    Text("Go to...")
                }
                Button("Open sheet") {
                    self.showSheet.toggle()
                }
            }
        }
        .sheet(isPresented: binding) {
            Text("Hello")
        }
    }
}

struct DetailView: View {
    @Binding var showSheet: Bool

    var body: some View {
        Button("Open sheet") {
            self.showSheet.toggle()
        }
    }
}