如何在SwiftUI MacOS应用程序中关闭DetailView而不关闭整个窗口?

qv7cva1a  于 2023-04-10  发布在  Swift
关注(0)|答案(1)|浏览(125)

下面是两个SwiftUI视图的示例,它们具有关闭窗口而不是关闭DetailView的意外行为:

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: DetailView()) {
                Text("Go to detail view")
            }
        }
    }
}

struct DetailView: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    
    var body: some View {
        Button(action: { presentationMode.wrappedValue.dismiss() }) {
            Text("Dismiss")
        }
    }
}

Ans here is the video showing this behavior.

jexiocij

jexiocij1#

您还可以使用NavigationSplitView来通知您NavigationView现在已弃用

struct ContentView: View {
    @State private var isDetailViewPresented = false
    var body: some View {
        NavigationSplitView {
            Button("Go to detail view") {
                isDetailViewPresented = true
            }
        } detail: {
            if  isDetailViewPresented {
                DetailView(isPresented: $isDetailViewPresented)
            }
        }
    }
}
    

struct DetailView: View {
    @Binding var isPresented: Bool
    var body: some View {
            VStack {
                Text("Detail View")
                Button(action: { isPresented.toggle()
                }) {
                    Text("Dismiss")
                }
            }
    }
}

相关问题