简体   繁体   中英

Show NSMenu when clicking on a Button in SwiftUI view

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM