Home > front end >  Calling a sheet from a menu item
Calling a sheet from a menu item

Time:02-13

I have a macOS app that has to display a small dialog with some information when the user presses the menu item "Info".

I've tried calling doing this with a .sheet but can't get it to display the sheet. Code:

@main
struct The_ThingApp: App {
    private let dataModel = DataModel()
    @State var showsAlert = false
    @State private var isShowingSheet = false

    var body: some Scene {
       WindowGroup {
          ContentView()
          .environmentObject(self.dataModel)
       }
       .commands {
            CommandMenu("Info") {
                Button("Get Info") { 
                    print("getting info")
                    isShowingSheet.toggle()
                }
                .sheet(isPresented: $isShowingSheet) {
                    VStack {
                        Text("Some stuff to be shown")
                            .font(.title)
                            .padding(50)
                        Button("Dismiss",
                               action: { isShowingSheet.toggle() })
                    }
                }
            }
       }
    }
}

How would I display a sheet from a menu item?

However, if a sheet is not the way to do it (I think given the simplicity of what I need to show, it would be it), how would you suggest I do it? I tried creating a new view, like I did with the preferences window, but I can't call it either from the menu.

CodePudding user response:

put the sheet directly on ContentView:

@main
struct The_ThingApp: App {
    
    @State private var isShowingSheet = false
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                // here VV
                .sheet(isPresented: $isShowingSheet) {
                    VStack {
                        Text("Some stuff to be shown")
                            .font(.title)
                            .padding(50)
                        Button("Dismiss",
                               action: { isShowingSheet.toggle() })
                    }
                }
        }
        
        .commands {
            CommandMenu("Info") {
                Button("Get Info") {
                    print("getting info")
                    isShowingSheet.toggle()
                }
            }
        }
    }
}
  • Related