![](/img/trans.png)
[英]Detect when a button is pressed outside of the IBAction in Swift?
[英]detect when button is pressed down and then up Swift macOS
我正在编写一个向机顶盒发送命令的应用程序。 盒子可以接收两种类型的命令:push 和 release。
我可以快速按下 macOS 上的按钮。 @IBAction func btnPressed(sender: NSButton) { } 在其中我发送命令和发布。 对于更改频道、静音或其他任何命令,一切正常。 相反,为了提高音量或完成音量,我需要通过做我所做的事情,单击几次以提高或降低音量。
我让鼠标上下工作,检测点击发生的位置(在 NSImageView 内(如果不是按钮)对应于向上和向下图像)以模拟长按向上或向下的音量,但我无法将其放入按钮按下方法。
'buttonpressed' 方法中是否有一种方法可以组合鼠标事件,以便在按住鼠标的同时模拟长按?
PS:我也在这里用谷歌搜索过,但没有找到提示。
如果它可以帮助:
1 子类化按钮类以触发mouseDown 和mouseUp 上的动作(该动作将被触发两次)
class myButton: NSButton {
override func awakeFromNib() {
super.awakeFromNib()
let maskUp = NSEvent.EventTypeMask.leftMouseUp.rawValue
let maskDown = NSEvent.EventTypeMask.leftMouseDown.rawValue
let mask = Int( maskUp | maskDown ) // cast from UInt
//shortest way for the above:
//let mask = NSEvent.EventTypeMask(arrayLiteral: [.leftMouseUp, .leftMouseDown]).rawValue
self.sendAction(on: NSEvent.EventTypeMask(rawValue: NSEvent.EventTypeMask.RawValue(mask)))
//objC gives: [self.button sendActionOn: NSLeftMouseDownMask | NSLeftMouseUpMask];
}
}
2:在storyboard中,将NSButton的类改为你的类:
3:将动作的发送者设置为您的子类并检查 currentEvent 类型:
@IBAction func volUpPressed(sender: myButton) {
let currEvent = NSApp.currentEvent
if(currEvent?.type == .leftMouseDown) {
print("volume Up pressed Down")
//... do your stuff here on mouseDown
}
else
if(currEvent?.type == .leftMouseUp) {
print("volume Up pressed Up")
//... do your stuff here on mouseUp
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.