检测何时按下按钮,然后按下Swift MacOS

问题描述

我正在编写一个将命令发送到机顶盒的应用程序。 该框可以接收两种类型的命令:推入和释放。

我可以迅速在macO上按下按钮。 @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:在情节提要中,将NSButton的类更改为您的类:

enter image description here

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
    }
}