Distinguishing a single click from a double click in Cocoa on the Mac

后端 未结 5 1007
一向
一向 2021-02-01 21:05

I have a custom NSView (it\'s one of many and they all live inside an NSCollectionView — I don\'t think that\'s relevant, but who knows). When I click

5条回答
  •  别那么骄傲
    2021-02-01 21:50

    @Dave DeLong's solution in Swift 4.2 (Xcode 10, macOS 10.13), amended for use with event.location(in: view)

    var singleClickPoint: CGPoint?
    
    override func mouseDown(with event: NSEvent) {
    singleClickPoint = event.location(in: self)
    perform(#selector(GameScene.singleClickAction), with: nil, afterDelay: NSEvent.doubleClickInterval)
     if event.clickCount == 2 {
        RunLoop.cancelPreviousPerformRequests(withTarget: self)
        singleClickPoint = nil
    //do whatever you want on double-click
    }
    }
    
    @objc func singleClickAction(){
    guard let singleClickPoint = singleClickPoint else {return}
    //do whatever you want on single-click
    }
    

    The reason I'm not using singleClickAction(at point: CGPoint) and calling it with: event.location(in: self) is that any point I pass in - including CGPoint.zero - ends up arriving in the singleClick Action as (0.0, 9.223372036854776e+18). I will be filing a radar for that, but for now, bypassing perform is the way to go. (Other objects seem to work just fine, but CGPoints do not.)

提交回复
热议问题