Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Present Modal via ContextMenu

I'm currently trying to present a modal view by pressing a button in the context menu. This works, but the code which should present the modal view is called twice and this is a problem, because I'm calling some networking requests.

Here is my currently demo project (without networking stuff):

This is the view which is called on app start.

struct ContentView: View {
    @State var isModal: Bool = false

    var body: some View {
        Group {
            Text("Main view")
        }.contextMenu {
            Button("Present Detail") { self.isModal = true }.sheet(isPresented: $isModal) {
                DetailView()
            }
        }
    }
}

This is the simple detail view

struct DetailView: View {
    var body: some View {
        Text("Detail View")
    }
}

So if I place a breakpoint at the line where the DetailView() is instantiated, I see that this part is called twice. Is there a better solution to present the modal view, without being instantiated multiple times?

like image 705
patrickS Avatar asked Sep 05 '25 02:09

patrickS


1 Answers

Use instead

var body: some View {
    Group {
        Text("Main view")
    }.contextMenu {
        Button("Present Detail") { self.isModal = true }
    }.sheet(isPresented: $isModal) {
        DetailView()
    }
}
like image 149
Asperi Avatar answered Sep 07 '25 20:09

Asperi