Show NSMenu when clicking on a Button in SwiftUI view

569 Views Asked by At

I'm trying to show a NSMenu when clicking on a Button in a SwiftUI view, but nothing is displayed with the code I'm using. Here it is:

HStack {
    Spacer(minLength: 100)
    Button(action: {
        let menu = NSMenu()
        menu.addItem(
            withTitle: "Quit",
            action: #selector(NSApp.terminate(_:)),
            keyEquivalent: "q")
        menu.popUp(
            positioning: nil,
            at: NSPoint.init(x: 50, y: 50),
            in: nil)
        }, label: {
            Image(systemName: "gear")
        })
        .buttonStyle(PlainButtonStyle()))
}

Nothing shows up, but I'm pretty sure I'm missing something important.

1

There are 1 best solutions below

1
Andrea Mario Lufino On

Following the suggestion of vanadian in the comment, the way to go is to use Menu to get the result. This is how I did:

HStack {
    Spacer(minLength: 100)
    
    Menu("") {
        Button("Menu.Preferences".localized) {
            NSApp.sendAction(Selector(("showPreferencesWindow:")), to: nil, from: nil)
        }
        Divider()
        Button("Menu.Quit".localized) {
            NSApp.terminate(self)
        }
    }
    .frame(width: 30)
    .menuStyle(BorderlessButtonMenuStyle())
}

This is a SwiftUI solution to reach the result I wanted.