[英]Show NSMenu when clicking on a Button in SwiftUI view
我試圖在 SwiftUI 視圖中單擊按鈕時顯示 NSMenu,但我正在使用的代碼沒有顯示任何內容。 這里是:
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()))
}
什么都沒有出現,但我很確定我錯過了一些重要的東西。
根據vanadian在評論中的建議,go的方法是使用Menu獲取結果。 我就是這樣做的:
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())
}
這是一個 SwiftUI 解決方案,可以達到我想要的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.