首页 > 解决方案 > 如何从 NavigationLink 中关闭工作表

问题描述

在下面的示例中,我有一个显示一张ViewOne. ViewOne有一个NavigationLinkViewTwo

我怎样才能解除工作表ViewTwo

使用presentationMode.wrappedValue.dismiss()导航回ViewOne.

struct ContentView: View {

    @State private var isShowingSheet = false

    var body: some View {
        Button("Show sheet", action: {
            isShowingSheet.toggle()
        })
        .sheet(isPresented: $isShowingSheet, content: {
            ViewOne()
        })
    }
}

struct ViewOne: View {

    var body: some View {
        NavigationView {
            NavigationLink("Go to ViewTwo", destination: ViewTwo())
                .isDetailLink(false)
        }
    }
}

struct ViewTwo: View {

    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Button("Dismiss sheet here") {
            presentationMode.wrappedValue.dismiss()
        }
    }
}

标签: swiftuiswiftui-navigationlinkswiftui-navigationviewswiftui-environment

解决方案


这可能取决于平台——NavigationView例如,在 macOS 上,您现有的代码可以工作。

将 a 显式传递Binding给原始工作表状态应该可以工作:

struct ContentView: View {

    @State private var isShowingSheet = false

    var body: some View {
        Button("Show sheet", action: {
            isShowingSheet.toggle()
        })
        .sheet(isPresented: $isShowingSheet, content: {
            ViewOne(showParentSheet: $isShowingSheet)
        })
    }
}

struct ViewOne: View {
    @Binding var showParentSheet : Bool
    
    var body: some View {
        NavigationView {
            NavigationLink("Go to ViewTwo", destination: ViewTwo(showParentSheet: $showParentSheet))
                //.isDetailLink(false)
        }
    }
}

struct ViewTwo: View {
    @Binding var showParentSheet : Bool
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Button("Dismiss sheet here") {
            showParentSheet = false
        }
    }
}

推荐阅读