gpt4 book ai didi

swift - 检测 NSStatusItem 上的左右点击事件(Swift)

转载 作者:搜寻专家 更新时间:2023-11-01 05:48:40 25 4
gpt4 key购买 nike

我正在构建一个状态栏应用程序,并希望根据用户是向左还是向右单击来调用不同的操作。这是我目前所拥有的:

var statusItem = NSStatusBar.system().statusItem(withLength: -1)
statusItem.action = #selector(AppDelegate.doSomeAction(sender:))

let leftClick = NSEventMask.leftMouseDown
let rightClick = NSEventMask.rightMouseDown

statusItem.button?.sendAction(on: leftClick)
statusItem.button?.sendAction(on: rightClick)

func doSomeAction(sender: NSStatusItem) {
print("hello world")
}

我的函数没有被调用,我找不到原因。感谢您的帮助!

最佳答案

你试过吗:

button.sendAction(on: [.leftMouseUp, .rightMouseUp])

然后查看在 doSomeAction() 函数中按下了哪个鼠标按钮?

所以它看起来像...

let statusItem = NSStatusBar.system().statusItem(withLength: NSSquareStatusItemLength)

func applicationDidFinishLaunching(_ aNotification: Notification) {

if let button = statusItem.button {
button.action = #selector(self.doSomeAction(sender:))
button.sendAction(on: [.leftMouseUp, .rightMouseUp])
}

}

func doSomeAction(sender: NSStatusItem) {

let event = NSApp.currentEvent!

if event.type == NSEvent.EventType.rightMouseUp {
// Right button click
} else {
// Left button click
}

}

感谢@dbrownjave 注意到 Swift 4 从 NSEventType.rightMouseUpNSEvent.EventType.rightMouseUp 的变化。

https://github.com/craigfrancis/datetime/blob/master/xcode/DateTime/AppDelegate.swift

关于swift - 检测 NSStatusItem 上的左右点击事件(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38999700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com