如何从 NavigationLink 中关闭 sheet

How to dismiss sheet from within NavigationLink

在下面的示例中,我有一个显示 sheet 为 ViewOne 的视图。 ViewOne 有一个 NavigationLinkViewTwo

如何关闭 ViewTwo 中的 sheet?

使用 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()
        }
    }
}

这可能取决于某些平台——例如,在 macOS 上的 NavigationView 中,您现有的代码有效。

Binding 显式传递给原始 sheet 状态应该可行:

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