【问题标题】:How to dismiss sheet from within NavigationLink如何从 NavigationLink 中关闭工作表
【发布时间】:2021-07-17 23:12:25
【问题描述】:

在以下示例中,我有一个显示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()
        }
    }
}

【问题讨论】:

标签: swiftui swiftui-navigationlink swiftui-navigationview swiftui-environment


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多