简体   繁体   English

在 SwiftUI 视图中单击按钮时显示 NSMenu

[英]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.我试图在 SwiftUI 视图中单击按钮时显示 NSMenu,但我正在使用的代码没有显示任何内容。 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.根据vanadian在评论中的建议,go的方法是使用Menu获取结果。 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.这是一个 SwiftUI 解决方案,可以达到我想要的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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